<?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 Facu Spagnuolo on Medium]]></title>
        <description><![CDATA[Stories by Facu Spagnuolo on Medium]]></description>
        <link>https://medium.com/@facuspagnuolo?source=rss-ecbaaacf79f8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4D_Exsguhs3wtk9-5GrMsQ.jpeg</url>
            <title>Stories by Facu Spagnuolo on Medium</title>
            <link>https://medium.com/@facuspagnuolo?source=rss-ecbaaacf79f8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:09:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@facuspagnuolo/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[Introducing Smart Vaults]]></title>
            <link>https://medium.com/mimicfi/introducing-smart-vaults-3438bacc843d?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3438bacc843d</guid>
            <category><![CDATA[smart-vaults]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[mimic]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 01:09:23 GMT</pubDate>
            <atom:updated>2023-07-10T21:26:34.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOrR_X8f02s1m2LCtRsmXQ.png" /></figure><p>Mimic is a platform that allows you to deploy tailored infrastructure to automate DeFi operations in a secure, trustless, and non-custodial way. These operations include treasury management, index rebalancing, fee distribution, liquidity provision, etc.</p><p>Mimic achieves this through an innovative concept called <strong>Smart Vaults</strong>, an automated solution where a list of allowed actions can be defined and customized to suit any operational need. Smart Vaults are multi-layer and can be easily scaled up by deploying and connecting additional ones.</p><p>Unlike other solutions, Mimic provides enormous flexibility to embrace this constantly-changing ecosystem, making any DeFi interaction experience much easier and more secure than before.</p><h3>How it works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZSEe9hjdUmzkYtvRl3HPw.png" /><figcaption>Smart vault high-level illustration</figcaption></figure><p>To implement Smart Vaults, Mimic offers a list of pre-set <strong>primitives</strong> that can be grouped into <strong>actions</strong> to model any type of process for your Smart Vaults.</p><p><strong>Primitives</strong> are pre-set atomic operations that can be executed on any Smart Vault, the main primitives are meant to cover the following concepts: collect, swap, bridge, join, exit, wrap, unwrap, withdraw, and call. Each primitive defines a set of parameters that can be configured for its execution. These can be forced to a hardcoded value, be limited within a specific range, or dynamically adjusted based on a network condition. For example, the slippage of a swap can be limited to a maximum value.</p><p>Moreover, to automate complex processes, primitives are not executed in isolation. As mentioned before, these can be grouped in different ways into <strong>actions</strong> to perform more complex operations. Actions can define how primitives are connected to each other and in which order these must be executed. Additionally, actions can be configured to base their execution depending on any transaction metadata like origin, gas price, gas cost, timestamps, etc. For example, an action can be configured to be executed only once a month, or only if its total gas cost is lower than 10 DAI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9IVjIz7xwaw4d4_RGrqEw.png" /><figcaption>Action example of how assets can be swapped and bridged from different layers to join an Ethereum protocol</figcaption></figure><p>These are just a few examples, Mimic opens the doors to model any other type of actions that could be automated to improve your DeFi experience.</p><h3>Architecture</h3><p>Smart Vaults are structured in different smart contract components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJkQ2YX-0N3l8uOSKAW3Ig.png" /><figcaption>Mimic Smart Vaults architecture</figcaption></figure><h3>Smart Vault</h3><p>This is the main component of the architecture, this is where all the assets are held and where their primitives are executed. This contract is also in charge of performing all the accounting logic related to investments and protocol fees. Smart Vaults also provide a built-in authentication logic to configure who is allowed to execute these primitives. Only allowed users can operate the Smart Vault’s assets, Mimic is never in control of their funds. Smart Vaults are replicated across different EVM-compatible chains to make sure users can interact with them transparently and in a unique way.</p><h4>Strategies</h4><p>Smart Vaults can use different strategies to allocate assets into different DeFi protocols. Strategies simply need to define how assets are allocated into a DeFi protocol, how to claim rewards to earn yield, and how to exit their position from the DeFi protocol. These can be managed dynamically, Smart Vaults are allowed to add or remove strategies to control their investment strategies at any time.</p><p>Mimic provides a standard interface to make sure all DeFi protocols can be accessed in a simple way from Smart Vaults. Additionally, Mimic facilitates a few implementations to integrate different DeFi protocols like Curve, AAVE, Balancer, Compound, Uniswap, and others. However, custom strategies can be developed in a really easy way. Any <a href="https://eips.ethereum.org/EIPS/eip-4626">ERC-4626</a> vault or similar vaults can be used as a Smart Vault strategy.</p><h4>Swap Connector</h4><p>The Swap Connector is a smart contract that simply assists the rest of the components in a Smart Vault to swap assets. Having this kind of logic in a separate contract allows Smart Vaults to update it or replace it with another implementation in the future if desired. For example, the Swap Connector may allow swapping in different exchanges initially but it also may want to support some more in the future.</p><p>The Swap Connector simply interfaces with external exchanges to swap assets and it is mainly used by Smart Vaults. For example, it allows Smart Vaults to swap assets to join strategies to have a better position or to swap rewards to re-invest them.</p><h4>Price Oracle</h4><p>The Price Oracle can be used to query the price of an asset in a decentralized way. It can be used along with other components to achieve different operations. For example, it can be used to compute the minimum amount out for a swap based on a given slippage before calling the Swap Connector. It serves as a second source of truth to avoid having Smart Vaults depending entirely on what the Swap Connector says. Similarly to the Swap Connector, Smart Vaults can update or replace this dependency with new implementations in the future if they need to.</p><h4>Mimic Registry</h4><p>The Mimic Registry is where all the implementations of the contracts listed above are registered. It acts as a curated on-chain registry so Smart Vaults can check against it before updating their dependencies. For example, there could be two available Swap Connector implementations registered in the Registry that offer different exchanges. If a Smart Vault wants to update its Swap Connector dependency from one to another, it can simply validate that change using the registry to make sure they are not pointing to an invalid or malicious Swap Connector instance.</p><h4>Actions</h4><p>As described before, actions are where primitives can be combined together to achieve more complex operations. Actions can be granted with Smart Vaults permissions to execute different primitives. An action is a simple smart contract with Smart Vaults permissions that executes a specific set of primitives in a specific order. Context predicates can be defined in each action to control when this should be executed. Moreover, similarly to Smart Vaults, actions also can make use of their built-in authentication logic to control who is allowed to execute these. For example, actions can be triggered by Mimic bots if they allow that.</p><h4>Bots</h4><p>Actions can be triggered not only manually, but also automatically by Mimic bots. Of course, this needs to be allowed from the Smart Vault itself beforehand. Smart Vaults can allow Mimic bots to execute certain actions based on their pre-set conditions. Bots will monitor the blockchain and trigger these actions automatically only if said pre-set conditions are met. For example, a Smart Vault could be set to withdraw gains every month. Note that this action can be configured to be executed automatically by a Mimic bot with a gas cost limit or gas price limit.</p><h3>What’s next</h3><p>We are currently having tons of conversations with many projects and DAOs that are interested in automating some of their DeFi interactions. Some of these are <a href="https://paraswap.io/">Paraswap</a>, <a href="https://balancer.finance/">Balancer</a>, <a href="https://dxdao.eth.link/">DXdao</a>, <a href="https://decentraland.org/">Decentraland</a>, <a href="https://aragon.org/">Aragon</a>, <a href="https://thegraph.com/">The Graph</a>, <a href="https://twitter.com/karpatkey">Karpatkey</a>, and others.</p><p>If you want to look deeper into what we achieved so far you can follow our open-source repositories in <a href="https://github.com/mimic-fi/">GitHub</a>. Even though all our smart contracts have been reviewed and supervised by security researchers, currently we are going through a formal audit process with one of the top firms in the industry. We will disclose the results and takeovers as soon as we finish the process. <strong>The status of our contracts is considered experimental and should be used at your own risk.</strong></p><p>Hopefully, soon we will be able to communicate a bug bounty program for the hacker community. However, if you found any potential issue in any of our smart contracts or in any piece of code you consider critical for the safety of the protocol, please contact us through <a href="/service/mailto:security@mimic.fi">security@mimic.fi</a>.</p><p><strong>Mimic Finance</strong></p><p><a href="https://www.mimic.fi/">Website</a> | <a href="https://docs.mimic.fi/">Docs</a> | <a href="https://discord.mimic.fi/">Discord</a> | <a href="https://twitter.com/mimicfi">Twitter</a> | <a href="https://github.com/mimic-fi">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3438bacc843d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mimicfi/introducing-smart-vaults-3438bacc843d">Introducing Smart Vaults</a> was originally published in <a href="https://medium.com/mimicfi">Mimic Protocol</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum in Depth, Part 2]]></title>
            <link>https://medium.com/@facuspagnuolo/ethereum-in-depth-part-2-6339cf6bddb9?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6339cf6bddb9</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 15:06:38 GMT</pubDate>
            <atom:updated>2019-02-13T20:53:13.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*39Qr9vBGWGPc1_Zw" /><figcaption>Photo by <a href="https://unsplash.com/@steve3p_0">Steve Halama</a> on <a href="https://unsplash.com/photos/QE3pKd1pO04">Unsplash</a>.</figcaption></figure><p>Welcome to the second part of this guide. If you haven’t read <a href="https://blog.zeppelin.solutions/ethereum-in-depth-part-1-968981e6f833">part 1</a>, I highly recommend it to better understand this post. This second article will explain everything about data management. We will see how memory, storage, calldata and stack data is manipulated.</p><p>To better understand this article, you should be familiar with the basics of the EVM. If you are not, I highly recommend reading <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094">these posts</a> first.</p><p>Throughout this post we will illustrate some examples and demonstrations using sample contracts you can find in <a href="https://github.com/facuspagnuolo/ethereum-in-depth">this repository</a>. Please clone it, run npm install, and check it out before beginning.</p><p><em>Enjoy, and please do not hesitate to reach out with questions, suggestions or feedback.</em></p><h3>Data Management</h3><p>The EVM manages different kinds of data depending on their context, and it does that in different ways. We can distinguish at least four main types of data: stack, calldata, memory, and storage, besides the contract code. Let’s analyze each of these:</p><h4>Stack</h4><p>The EVM is a stack machine, meaning that it doesn’t operate on registers but on a virtual stack. The stack has a maximum size of 1024. Stack items have a size of 256 bits; in fact, the EVM is a 256-bit word machine (this facilitates Keccak256 hash scheme and elliptic-curve computations). Here is where most opcodes consume their parameters from.</p><p>The EVM provides many opcodes to modify the stack directly. Some of these include:</p><ul><li>POP removes item from the stack.</li><li>PUSH<em>n</em> places the following <em>n</em> bytes item in the stack, with <em>n</em> from 1 to 32.</li><li>DUP<em>n</em> duplicates the <em>n</em>th stack item, with <em>n</em> from 1 to 32.</li><li>SWAP<em>n</em> exchanges the 1st and <em>n</em>th stack item, with <em>n</em> from 1 to 32.</li></ul><h4>Calldata</h4><p>The calldata is a read-only byte-addressable space where the data parameter of a transaction or call is held. Unlike the stack, to use this data you have to specify an exact byte offset and number of bytes you want to read.</p><p>The opcodes provided by the EVM to operate with the calldata include:</p><ul><li>CALLDATASIZE tells the size of the transaction data.</li><li>CALLDATALOAD<em> </em>loads 32 bytes of the transaction data onto the stack.</li><li>CALLDATACOPY<em> </em>copies a number of bytes of the transaction data to memory.</li></ul><p>Solidity also provides an inline assembly version of these opcodes. These are calldatasize, calldataload and calldatacopy respectively. The last one expects three arguments (t, f, s): it will copy s bytes of calldata at position f into memory at position t. In addition, Solidity lets you access to the calldata through msg.data.</p><p>As you may have noticed, we used some of these opcodes in some examples of the previous post. Let’s take a look at the inline assembly code block of a delegatecall again:</p><pre>assembly {<br>  let ptr := mload(0x40)<br>  calldatacopy(ptr, 0, calldatasize)<br>  let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)<br>}</pre><p>To delegate the call to the _impl address, we must forward msg.data. Given that the delegatecall opcode operates with data in memory, we need to copy the calldata into memory first. That’s why we use calldatacopy to copy all the calldata to a memory pointer (note that we are using calldatasize).</p><p>Let’s analyze another example using calldata. You will find a Calldata contract in the <a href="https://github.com/facuspagnuolo/ethereum-in-depth/blob/master/3-data-management/">exercise 3</a> folder with the following code:</p><pre>contract Calldata {</pre><pre>  function add(uint256 _a, uint256 _b) public view <br>  returns (uint256 result) <br>  {<br>    assembly {<br>      let a := mload(0x40)<br>      let b := add(a, 32)<br>      calldatacopy(a, 4, 32)<br>      calldatacopy(b, add(4, 32), 32)<br>      result := add(mload(a), mload(b))<br>    }<br>  }<br>}</pre><p>The idea here is to return the addition of two numbers passed by arguments. As you can see, once again we are loading a memory pointer reading from 0x40, but please ignore that for now; we will explain it right after this example. We are storing that memory pointer in the variable a and storing in b the following position which is 32-bytes right after a. Then we use calldatacopy to store the first parameter in a. You may have noticed we are copying it from the 4th position of the calldata instead of its beginning. This is because the first 4 bytes of the calldata hold the <a href="https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector">signature of the function</a> being called, in this case bytes4(keccak256(&quot;add(uint256,uint256)&quot;)); this is what the EVM uses to identify which function has to be executed on a call. Then, we store the second parameter in b copying the following 32 bytes of the calldata. Finally, we just need to calculate the addition of both values loading them from memory.</p><p>You can test this yourself with a truffle console running the following commands:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; Calldata.new().then(i =&gt; calldata = i)<br>truffle(develop)&gt; calldata.add(1, 6).then(r =&gt; r.toString())    <strong>// 7</strong></pre><h4>Memory</h4><p>Memory is a volatile read-write byte-addressable space. It is mainly used to store data during execution, mostly for passing arguments to internal functions. Given this is volatile area, every message call starts with a cleared memory. All locations are initially defined as zero. As calldata, memory can be addressed at byte level, but can only read 32-byte words at a time.</p><p>Memory is said to “expand” when we write to a word in it that was not previously used. Additionally to the cost of the write itself, there is a cost to this expansion, which increases linearly for the first 724 bytes and quadratically after that.</p><p>The EVM provides three opcodes to interact with the memory area:</p><ul><li>MLOAD loads a word from memory into the stack.</li><li>MSTORE<em> </em>saves a word to memory.</li><li>MSTORE8 saves a byte to memory.</li></ul><p>Solidity also provides an inline assembly version of these opcodes.</p><p>There is another key thing we need to know about memory. Solidity always stores a free memory pointer at position 0x40, i.e. a reference to the first unused word in memory. That’s why we load this word to operate with inline assembly. Since the initial 64 bytes of memory are reserved for the EVM, this is how we can ensure that we are not overwriting memory that is used internally by Solidity. For instance, in the delegatecall example presented above, we were loading this pointer to store the given calldata to forward it. This is because the inline-assembly opcode delegatecall needs to fetch its payload from memory.</p><p>Additionally, if you pay attention to the bytecode output by the Solidity compiler, you will notice that all of them start with 0x6060604052…, which means:</p><pre>PUSH1   :  EVM opcode is 0x60<br>0x60    :  The free memory pointer<br>PUSH1<em>   </em>: <em> </em>EVM opcode is 0x60<br>0x40<em>    </em>:  Memory position for the free memory pointer<br>MSTORE  :  EVM opcode is 0x52</pre><p>You must be very careful when operating with memory at assembly level. Otherwise, you could overwrite a reserved space.</p><h4>Storage</h4><p>Storage is a persistent read-write word-addressable space. This is where each contract stores its persistent information. Unlike memory, storage is a persistent area and can only be addressed by words. It is a key-value mapping of 2²⁵⁶ slots of 32 bytes each. A contract can neither read nor write to any storage apart from its own. All locations are initially defined as zero.</p><p>The amount of gas required to save data into storage is one of the highest among operations of the EVM. This cost is not always the same. Modifying a storage slot from a zero value to a non-zero one costs 20,000. While storing the same non-zero value or setting a non-zero value to zero costs 5,000. However, in the last scenario when a non-zero value is set to zero, a refund of 15,000 will be given.</p><p>The EVM provides two opcodes to operate the storage:</p><ul><li>SLOAD loads a word from storage into the stack.</li><li>SSTORE<em> </em>saves a word to storage.</li></ul><p>These opcodes are also supported by the inline assembly of Solidity.</p><p>Solidity will automatically map every defined state variable of your contract to a slot in storage. The strategy is fairly simple — statically sized variables (everything except mappings and dynamic arrays) are laid out contiguously in storage starting from position 0.</p><p>For dynamic arrays, this slot (p) stores the length of the array and its data will be located at the slot number that results from hashing p (keccak256(p)). For mappings, this slot is unused and the value corresponding to a key k will be located at keccak256(k,p). Bear in mind that the parameters of keccak256 (k and p) are always padded to 32 bytes.</p><p>Let’s take a look at a code example to understand how this works. Inside the <a href="https://github.com/facuspagnuolo/ethereum-in-depth/blob/master/3-data-management/">exercise 3</a> contracts folder you will find a Storage contract with the following code:</p><pre>contract Storage {</pre><pre>  uint256 public number;<br>  address public account;<br>  uint256[] private array;<br>  mapping(uint256 =&gt; uint256) private map;</pre><pre>  function Storage() public {<br>    number = 2;<br>    account = this;<br>    array.push(10);<br>    array.push(100);<br>    map[1] = 9;<br>    map[2] = 10;<br>  }<br>}</pre><p>Now, let’s open a truffle console to test its storage structure. First, we will compile and create a new contract instance:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; Storage.new().then(i =&gt; storage = i)</pre><p>Then we can ensure that the address 0 holds a number 2 and the address 1 holds the address of the contract:</p><pre>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, 0)  // <strong>0x02<br></strong>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, 1)  // <strong>0x..</strong></pre><p>We can check that the storage position 2 holds the length of the array as follows:</p><pre>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, 2)  // <strong>0x02</strong></pre><p>Finally, we can check that the storage position 3 is unused and the mapping values are stored as we described above:</p><pre>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, 3) <br>// <strong>0x00</strong></pre><pre>truffle(develop)&gt; mapIndex = ‘0000000000000000000000000000000000000000000000000000000000000003’</pre><pre>truffle(develop)&gt; firstKey = ‘0000000000000000000000000000000000000000000000000000000000000001’</pre><pre>truffle(develop)&gt; firstPosition = web3.sha3(firstKey + mapIndex, { encoding: ‘hex’ })</pre><pre>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, firstPosition)<br>// <strong>0x09</strong></pre><pre>truffle(develop)&gt; secondKey = ‘0000000000000000000000000000000000000000000000000000000000000002’</pre><pre>truffle(develop)&gt; secondPosition = web3.sha3(secondKey + mapIndex, { encoding: ‘hex’ })</pre><pre>truffle(develop)&gt; web3.eth.getStorageAt(storage.address, secondPosition)<br>// <strong>0x0A</strong></pre><p>Great! We have demonstrated that the Solidity storage strategy works as we understand it! To learn more about how Solidity maps state variables into the storage, read the <a href="https://solidity.readthedocs.io/en/v0.4.23/miscellaneous.html#layout-of-state-variables-in-storage">official documentation</a>.</p><p>Thank you for reading this post, please remember any questions, feedback or suggestions are welcome!</p><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6339cf6bddb9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum in Depth, Part 1]]></title>
            <link>https://medium.com/@facuspagnuolo/ethereum-in-depth-part-1-968981e6f833?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/968981e6f833</guid>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[evm]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Fri, 11 May 2018 14:40:37 GMT</pubDate>
            <atom:updated>2019-02-13T20:53:58.523Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*vcPe7PrwSGfbERms." /><figcaption>Photo by <a href="https://unsplash.com/@bparish">Bryn Parish</a> on <a href="https://unsplash.com/photos/IDXsYT5xVEE">Unsplash</a>.</figcaption></figure><p>Welcome to the first part of a two-posts series aimed at software developers looking to understand how the EVM works. The idea is to explain and describe in detail core behavior of the EVM. We will see how contracts are created, how message calls work, and take a look at everything related to data management, such as storage, memory, calldata, and the stack.</p><p>To better understand this article, you should be familiar with the basics of the EVM. If you are not, I highly recommend reading <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094">these posts</a> first.</p><p>Throughout this post we will illustrate some examples and demonstrations using sample contracts you can find in <a href="https://github.com/facuspagnuolo/ethereum-in-depth">this repository</a>. Please clone it, run npm install, and check it out before beginning.</p><p><em>Enjoy, and please do not hesitate to reach out with questions, suggestions or feedback.</em></p><h3>Ethereum Contracts</h3><h4>Basics</h4><p>Smart contracts are just computer programs, and we can say that Ethereum contracts are smart contracts that run on the Ethereum Virtual Machine. The EVM is the sandboxed runtime and a completely isolated environment for smart contracts in Ethereum. This means that every smart contract running inside the EVM has no access to the network, file system, or other processes running on the computer hosting the VM.</p><p>As we already know, there are two kinds of accounts: contracts and external accounts. Every account is identified by an address, and all accounts share the same address space. The EVM handles addresses of 160-bit length. Every account consists of a balance, a nonce, bytecode, and stored data (<em>storage</em>). However, there are some differences between these two kinds of accounts. For instance, the code and storage of external accounts are empty, while contract accounts store their bytecode and the merkle root hash of the entire state tree. Moreover, while external addresses have a corresponding private key, contract accounts don’t. The actions of contract accounts are controlled by the code they host in addition to regular cryptographic signing of every Ethereum transaction.</p><h4>Creation</h4><p>The creation of a contract is simply a transaction in which the receiver address is empty and its data field contains the compiled bytecode of the contract to be created (this makes sense — contracts can create contracts too). Let’s look at a quick example. Please open the directory of <a href="https://github.com/facuspagnuolo/ethereum-in-depth/tree/master/1-contract-creation">exercise 1</a>; in it you will find a contract called MyContract with the following code:</p><pre>pragma solidity ^0.4.21;</pre><pre>contract MyContract {<br>  event Log(address addr);</pre><pre>  function MyContract() public {<br>    emit Log(this);<br>  }</pre><pre>  function add(uint256 a, uint256 b) public pure returns (uint256) {<br>    return a + b;<br>  }<br>}</pre><p>Let’s open a truffle console in develop mode running truffle develop. Once inside, follow the subsequent commands to deploy an instance of MyContract:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; sender = web3.eth.accounts[0]<br>truffle(develop)&gt; opts = { from: sender, to: null, data: MyContract.bytecode, gas: 4600000 }<br>truffle(develop)&gt; txHash = web3.eth.sendTransaction(opts)</pre><p>We can check that our contract has been deployed successfully by running the following code:</p><pre>truffle(develop)&gt; receipt = web3.eth.getTransactionReceipt(txHash)<br>truffle(develop)&gt; myContract = new MyContract(receipt.contractAddress)<br>truffle(develop)&gt; myContract.add(10, 2)</pre><pre><strong><em>{ [String: ‘12’] s: 1, e: 1, c: [ 12 ] }</em></strong></pre><p>Let’s go deeper to analyze what we just did. The first thing that happens when a new contract is deployed to the Ethereum blockchain is that its account is created.¹ As you can see, we logged the address of the contract in the constructor in the example above. You can confirm this by checking that receipt.logs[0].data is the address of the contract-padded 32 bytes and that receipt.logs[0].topics is the keccak-256 hash of the string “Log(address)”.</p><p>As the next step, the data sent in with the transaction is executed as bytecode. This will initialize the state variables in storage, and determine the body of the contract being created. This process is executed only once during the lifecycle of a contract. The initialization code is not what is stored in the contract; it actually produces as its return value the bytecode to be stored. Bear in mind that after a contract account has been created, there is no way to change its code.²</p><p>Given the fact that the initialization process returns the code of the contract’s body to be stored, it makes sense that this code isn’t reachable from the constructor logic. For example, let’s take a look at the Impossible contract of <a href="https://github.com/facuspagnuolo/ethereum-in-depth/tree/master/1-contract-creation">exercise 1</a>:</p><pre>contract Impossible {<br>  function Impossible() public {<br>    this.test();<br>  }</pre><pre>  function test() public pure returns(uint256) {<br>    return 2;<br>  }<br>}</pre><p>If you try to compile this contract, you will get a warning saying you’re referencing this within the constructor function, but it will compile. However, if you try to deploy a new instance, it will revert. This is because it makes no sense to attempt to run code that is not stored yet.³ On the other hand, we were able to access the address of the contract: the account exists, but it doesn’t have any code yet.</p><p>However, a code execution can produce other events, such as altering the storage, creating further accounts, or making further message calls. For example, let’s take a look at the AnotherContract code:</p><pre>contract AnotherContract {<br>  MyContract public myContract;<br>  function AnotherContract() public {<br>    myContract = new MyContract();<br>  }<br>}</pre><p>Let’s see how it works running the following commands inside a truffle console:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; sender = web3.eth.accounts[0]<br>truffle(develop)&gt; opts = { from: sender, to: null, data: AnotherContract.bytecode, gas: 4600000 }<br>truffle(develop)&gt; txHash = web3.eth.sendTransaction(opts)<br>truffle(develop)&gt; receipt = web3.eth.getTransactionReceipt(txHash)<br>truffle(develop)&gt; anotherContract = AnotherContract.at(receipt.contractAddress)<br>truffle(develop)&gt; anotherContract.myContract().then(a =&gt; myContractAddress = a)<br>truffle(develop)&gt; myContract = MyContract.at(myContractAddress)<br>truffle(develop)&gt; myContract.add(10, 2)</pre><pre><strong><em>{ [String: ‘12’] s: 1, e: 1, c: [ 12 ] }</em></strong></pre><p>Additionally, contracts can be created using the CREATE opcode, which is what the Solidity new construct compiles down to. Both alternatives work the same way. Let’s continue exploring how message calls work.</p><h4>Message Calls</h4><p>Contracts can call other contracts through message calls. Every time a Solidity contract calls a function of another contract, it does so by producing a message call. Every call has a sender, a recipient, a payload, a value, and an amount of gas. Solidity provides a native call method for the address type that works as follows:</p><p><em>address</em>.call.gas(<em>gas</em>).value(<em>value</em>)(<em>data</em>)</p><p>gas is the amount of gas to be forwarded, address is the address to be called, value is the amount of Ether to be transferred in wei, and data is the payload to be sent. Bear in mind that value and gas are optional parameters here, but be careful because almost all the remaining gas of the sender will be sent by default in a low-level call.</p><p>As you can see, each contract can decide the amount of gas to be forwarded in a call. Given that every call can end in an out-of-gas (OOG) exception, to avoid security issues at least 1/64th of the sender’s remaining gas will be saved. This allows senders to handle inner calls’ out-of-gas errors, so that they are able to finish its execution without themselves running out of gas, and thus bubbling the exception up.</p><p>Let’s take a look at the Caller contract of <a href="https://github.com/facuspagnuolo/ethereum-in-depth/tree/master/2-message-calls">exercise 2</a>:</p><pre>contract Implementation {<br>  event ImplementationLog(uint256 gas);</pre><pre>  function() public payable {<br>    emit ImplementationLog(gasleft());<br>    assert(false);<br>  }<br>}</pre><pre>contract Caller {<br>  event CallerLog(uint256 gas);<br>  Implementation public implementation;<br>  <br>  function Caller() public {<br>    implementation = new Implementation();<br>  }</pre><pre>function () public payable {<br>    emit CallerLog(gasleft());<br>    implementation.call.gas(gasleft()).value(msg.value)(msg.data);<br>    emit CallerLog(gasleft());<br>  }<br>}</pre><p>The Caller contract has only a fallback function that redirects every received call to an instance of Implementation. This instance simply throws through an assert(false) on every received call, which will consume all the gas given. Then, the idea here is to log the amount of gas in Caller before and right after forwarding a call to Implementation. Let’s open a truffle console and see what happens:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; Caller.new().then(i =&gt; caller = i)<br>truffle(develop)&gt; opts = { gas: 4600000 }<br>truffle(develop)&gt; caller.sendTransaction(opts).then(r =&gt; result = r)<br>truffle(develop)&gt; logs = result.receipt.logs<br>truffle(develop)&gt; parseInt(logs[0].data) <strong>//<em>4578955<br></em></strong>truffle(develop)&gt; parseInt(logs[1].data) <strong>//<em>71495</em></strong></pre><p>As you can see, <strong><em>71495</em></strong> is approximately the 64th part of <strong><em>4578955</em></strong>. This example clearly demonstrates that we can handle an OOG exception from an inner call.</p><p>Solidity also provides the following opcode, allowing us to manage calls with inline assembly:</p><p>call(g, a, v, in, insize, out, outsize)</p><p>Where g is the amount of gas to be forwarded, a is the address to be called, v is the amount of Ether to be transferred in wei, in states the memory position of insize bytes where the call data is held, and out and outsize state where the return data will be stored in memory. The only difference is that an assembly call allows us to handle return data, while the function will only return 1 or 0 whether it failed or not.</p><p>The EVM supports a special variant of a message call called delegatecall. Once again, Solidity provides a built-in address method in addition to an inline assembly version of it. The difference with a low-level call is that the target code is executed within the context of the calling contract, and msg.sender and msg.value do not change.⁴</p><p>Let’s analyze the following example to understand better how a delegatecall works. Let’s start with the Greeter contract:</p><pre>contract Greeter {<br>  event Thanks(address sender, uint256 value);</pre><pre>  function thanks() public payable {<br>    emit Thanks(msg.sender, msg.value);<br>  }<br>}</pre><p>As you can see, the Greeter contract simply declares a thanks function that emits an event carrying the msg.value and msg.sender data. We can try this method by running the following lines in a truffle console:</p><pre>truffle(develop)&gt; compile<br>truffle(develop)&gt; someone = web3.eth.accounts[0]<br>truffle(develop)&gt; ETH_2 = new web3.BigNumber(‘2e18’)<br>truffle(develop)&gt; Greeter.new().then(i =&gt; greeter = i)<br>truffle(develop)&gt; opts = { from: someone, value: ETH_2 }<br>truffle(develop)&gt; greeter.thanks(opts).then(tx =&gt; log = tx.logs[0])<br>truffle(develop)&gt; log.event                     <strong>//Thanks<br></strong>truffle(develop)&gt; log.args.sender === someone   <strong>//true<br></strong>truffle(develop)&gt; log.args.value.eq(ETH_2)      <strong>//true</strong></pre><p>Now that we have confirmed its functionality, let’s pay attention to the Wallet contract:</p><pre>contract Wallet {<br>  Greeter internal greeter;<br>  <br>  function Wallet() public {<br>    greeter = new Greeter();<br>  }<br>  <br>  function () public payable {<br>    bytes4 methodId = Greeter(0).thanks.selector;<br>    require(greeter.delegatecall(methodId));<br>  }<br>}</pre><p>This contract only defines a fallback function that executes the Greeter#thanks method through a delegatecall. Let’s see what happens when we call Greeter#thanks through the Wallet contract:</p><pre>truffle(develop)&gt; Wallet.new().then(i =&gt; wallet = i)<br>truffle(develop)&gt; wallet.sendTransaction(opts).then(r =&gt; tx = r)<br>truffle(develop)&gt; logs = tx.receipt.logs<br>truffle(develop)&gt; SolidityEvent = require(‘web3/lib/web3/event.js’)<br>truffle(develop)&gt; Thanks = Object.values(Greeter.events)[0]<br>truffle(develop)&gt; event = new SolidityEvent(null, Thanks, 0)<br>truffle(develop)&gt; log = event.decode(logs[0])<br>truffle(develop)&gt; log.event                    <strong>// Thanks<br></strong>truffle(develop)&gt; log.args.sender === someone  <strong>// true<br></strong>truffle(develop)&gt; log.args.value.eq(ETH_2)     <strong>// true</strong></pre><p>As you may have noticed, we have just confirmed that the delegatecall function preserves the msg.value and msg.sender .</p><blockquote>This means that a contract 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. This makes it possible to implement the ‘library’ feature in Solidity.” ⁵</blockquote><p>There is one more thing we should explore about delegatecalls. As mentioned above, the storage of the calling contract is the one being accessed by the executed code. Let’s see the Calculator contract:</p><pre>contract ResultStorage {<br>  uint256 public result;<br>}</pre><pre>contract Calculator is ResultStorage {<br>  Product internal product;<br>  Addition internal addition;</pre><pre>  function Calculator() public {<br>    product = new Product();<br>    addition = new Addition();<br>  }<br>  <br>  function add(uint256 x) public {<br>    bytes4 methodId = Addition(0).calculate.selector;<br>    require(addition.delegatecall(methodId, x));<br>  }</pre><pre>  function mul(uint256 x) public {<br>    bytes4 methodId = Product(0).calculate.selector;<br>    require(product.delegatecall(methodId, x));<br>  }<br>}</pre><pre>contract Addition is ResultStorage {<br>  function calculate(uint256 x) public returns (uint256) {<br>    uint256 temp = result + x;<br>    assert(temp &gt;= result);<br>    result = temp;<br>    return result;<br>  }<br>}</pre><pre>contract Product is ResultStorage {<br>  function calculate(uint256 x) public returns (uint256) {<br>    if (x == 0) result = 0;<br>    else {<br>      uint256 temp = result * x;<br>      assert(temp / result == x);<br>      result = temp;<br>    }<br>    return result;<br>  }<br>}</pre><p>The Calculator contract has just two functions: add and product. The Calculator contract doesn’t know how to add or multiply; it delegates those calls to the Addition and Product contracts respectively instead. However, all these contracts share the same state variable result to store the result of each calculation. Let’s see how this works:</p><pre>truffle(develop)&gt; Calculator.new().then(i =&gt; calculator = i)<br>truffle(develop)&gt; calculator.addition().then(a =&gt; additionAddress=a)<br>truffle(develop)&gt; addition = Addition.at(additionAddress)<br>truffle(develop)&gt; calculator.product().then(a =&gt; productAddress = a)<br>truffle(develop)&gt; product = Product.at(productAddress)<br>truffle(develop)&gt; calculator.add(5)<br>truffle(develop)&gt; calculator.result().then(r =&gt; r.toString()) <strong>// 5<br></strong>truffle(develop)&gt; addition.result().then(r =&gt; r.toString())   <strong>// 0<br></strong>truffle(develop)&gt; product.result().then(r =&gt; r.toString())    <strong>// 0<br></strong>truffle(develop)&gt; calculator.mul(2)<br>truffle(develop)&gt; calculator.result().then(r =&gt; r.toString()) <strong>// 10<br></strong>truffle(develop)&gt; addition.result().then(r =&gt; r.toString())   <strong>// 0<br></strong>truffle(develop)&gt; product.result().then(r =&gt; r.toString())    <strong>// 0</strong></pre><p>We have just confirmed that we are using the storage of the Calculator contract. Besides that, the code being executed is stored in the Addition and in the Product contracts.</p><p>Additionally, as for the call function, there is a Solidity assembly opcode version for delegatecall. Let’s take a look at the Delegator contract to see how we can use it:</p><pre>contract Implementation {<br>  event ImplementationLog(uint256 gas);</pre><pre>function() public payable {<br>    emit ImplementationLog(gasleft());<br>    assert(false);<br>  }<br>}</pre><pre>contract Delegator {<br>  event DelegatorLog(uint256 gas);<br>  Implementation public implementation;</pre><pre>  function Delegator() public {<br>    implementation = new Implementation();<br>  }</pre><pre>  function () public payable {<br>    emit DelegatorLog(gasleft());<br>    address _impl = implementation;</pre><pre>    assembly {<br>     let ptr := mload(0x40)<br>     calldatacopy(ptr, 0, calldatasize)<br>     let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)<br>    }<br>   <br>    emit DelegatorLog(gasleft());<br>  }<br>}</pre><p>This time we are using inline assembly to execute the delegatecall. As you may have noticed, there is no value argument here, since msg.value will not change. You may be wondering why we are loading the 0x40 address, or what calldatacopy and calldatasize are. Don’t panic — we will describe them in the next post of the series. In the meantime, feel free to run the same commands over a truffle console to validate its behavior.</p><p>Once again, it’s important to understand clearly how a delegatecall works. Every triggered call will be sent from the current contract and not the delegate-called contract. Additionally, the executed code can read and write to the storage of the caller contract. You can view this as a cliffhanger for the next post, in which storage will be described in more detail.</p><p>Thank you for reading this post! We have learned more in-depth details about how smart contracts work in the Ethereum world. Please remember that questions, feedback, and suggestions are welcome! If you liked the post, stay tuned for the <a href="https://blog.zeppelin.solutions/ethereum-in-depth-part-2-6339cf6bddb9">second part</a> focused on data management!</p><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><p>¹ “The address of the new account is defined as being the rightmost 160 bits of the Keccak hash of the RLP encoding of the structure containing only the sender and the account nonce.” (<a href="https://ethereum.github.io/yellowpaper/paper.pdf">Ethereum Yellow Paper</a>)</p><p>² One of the pillars of zeppelin_os is contract upgradeability. At Zeppelin, we’ve been exploring different strategies to implement this. You can read more about this <a href="https://blog.zeppelinos.org/proxy-patterns/">here</a>.</p><p>³ Solidity will check before calling an external function that the address has bytecode in it, and otherwise revert.</p><p>⁴ This is the main strategy being used these days to build upgradeable contracts.</p><p>⁵ Solidity 0.4.23 <a href="https://solidity.readthedocs.io/en/v0.4.23/introduction-to-smart-contracts.html?highlight=delegatecall#delegatecall-callcode-and-libraries">official documentation</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968981e6f833" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Ethereum Programming, Part 3]]></title>
            <link>https://medium.com/@facuspagnuolo/a-gentle-introduction-to-ethereum-programming-part-3-abdd9644d0c2?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/abdd9644d0c2</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[zeppelin]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Fri, 12 Jan 2018 18:49:01 GMT</pubDate>
            <atom:updated>2019-02-13T20:54:37.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4p5wKn1FhiYflHrMaMJKQ.jpeg" /></figure><p>This is the third part of our Ethereum introduction guide. If you haven’t read parts <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094">1</a> and <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953">2</a>, I highly recommend them to better understand this post.</p><p><em>Enjoy, and please do not hesitate to reach out with questions, corrections or feedback.</em></p><h3>Index</h3><p><strong>1. </strong><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094"><strong>Taking the first steps</strong></a></p><p><strong>2. </strong><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953"><strong>Interacting with a contract</strong></a></p><p><strong>3. Frameworks &amp; Tools in the real world</strong></p><p>3.1. Deploying with Truffle</p><p>3.2. Testing smart contracts</p><p>3.3. OpenZeppelin</p><p><strong>4. A real DApp, a token marketplace — </strong><em>coming soon</em></p><h3>3. Frameworks &amp; Tools in the real world</h3><p>As you may have noticed, most of the work that we’ve been doing was pretty manual. Although this is a young industry, there are some tools that will make development easier. Let’s see some of them.</p><h4>3.1. Deploying with Truffle</h4><p>Until now, the only way we used to interact with our contracts was to deploy them manually through a Node console into a testrpc node and then load them using Web3. Now, let me introduce <a href="http://truffleframework.com/">Truffle</a> to you. It is an Ethereum development framework that will help us debugging, deploying, and testing smart contracts, among other things.</p><p>The first thing we’re going to do is to deploy a contract using Truffle. Let&#39;s create a new directory for this exercise and run the following commands to install Truffle and initialize our project:</p><pre>$ mkdir truffle-experiment<br>$ cd truffle-experiment/<br>$ npm install truffle@4.0.4<br>$ npx truffle init</pre><p>You will see some folders and files were created. Our directory should look like:</p><pre>truffle-experiment/<br>├── contracts/<br>│   └── Migrations.sol<br>├── migrations/<br>│   └── 1_initial_migration.js<br>├── test/<br>├── truffle.js<br>└── truffle-config.js</pre><p>The contracts folder is where the smart contracts should be. The migrations folder will host javascript files that will help us deploying our contracts to the network. You may also have seen a Migrations contract in the first folder, this is where the history of our migrations is going to be stored on-chain. The test folder is initially empty and is intended to keep our test files. Finally, you will see a truffle.js and a truffle-config.js files. We will skip them by now, but you can read more in <a href="http://truffleframework.com/docs/">their documentation</a>.</p><p>Now, let’s leave that boring stuff behind and focus on the interesting parts. To see an example of how we can deploy a contract using Truffle, we can use the same <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953#9b33">token contract</a> example from the previous post of this guide. Please grab that code and paste it into a MyToken.sol file inside the contracts folder. Then, create a new migration file called 2_deploy_my_token.js file and copy the following lines into it:</p><pre>const MyToken = artifacts.require(&#39;./MyToken.sol&#39;)</pre><pre>module.exports = function(deployer) {<br>  deployer.deploy(MyToken)<br>}</pre><p>As you can see, that migration will just deploy our token to the network. This time, we won’t need a testrpc node running since Truffle already comes with a simulation node for development and testing purposes. We just need to open a development console running npx truffle develop and run the migrations using truffle migrate inside it. Then, you should see an output like this:</p><pre>truffle(develop)&gt; truffle migrate</pre><pre>Using network ‘develop’.</pre><pre>Running migration: 1_initial_migration.js<br>Deploying Migrations…<br>… 0xf5776c9f32a9b5b7600d88a6a24b0ef433f559c31aaeb5eaf6e2fc5e2f7fa669<br>Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0<br>Saving successful migration to network…<br>… 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956<br>Saving artifacts…</pre><pre>Running migration: 2_deploy_my_token.js<br>Deploying MyToken…<br>… 0xc74019c2fe3b3ef1d4e2033c2e4b9fa13611f3150f8b6b37334a8e29e24b056c<br><strong>MyToken: 0x345ca3e014aaf5dca488057592ee47305d9b3e10</strong><br>Saving successful migration to network…<br>… 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0<br>Saving artifacts…</pre><p>We’ll just care about the line MyToken: 0x345ca3e0...305d9b3e10, which tells us the address of our deployed token contract. By default, Truffle initializes the simulation node with 10 addresses with fake ETH as we saw when using testrpc, and we can access this array via web3.eth.accounts. Moreover, it deploys these contracts using the first address of this list (the one with index 0), which means that it will be the owner of MyToken.</p><p>Given that Web3 is available inside the Truffle console, you can just run the following commands to check the owner’s balance:</p><pre>truffle(develop)&gt; owner = web3.eth.accounts[0]<br>truffle(develop)&gt; instance = MyToken.at(&#39;[DEPLOYED_ADDRESS]&#39;)<br>truffle(develop)&gt; instance.balanceOf(owner)</pre><p><strong><em>Note:</em></strong><em> Please remember to replace </em><em>[DEPLOYED_ADDRESS] by the address of the deployed contract given by Truffle, in this case: </em>0x345ca3e0...305d9b3e10.</p><p>We can also send some tokens to another address and then check the updated balances:</p><pre>// send tokens<br>amount = 10<br>recipient = web3.eth.accounts[1]<br>txHash = instance.sendTokens(recipient, amount, { from: owner })</pre><pre>// check balances<br>instance.balanceOf(owner)<br>instance.balanceOf(recipient)</pre><p>We’ve seen the recipient account now has 10 tokens! We can search the transaction information with the following line of code:</p><pre>web3.eth.getTransaction(txHash)</pre><h4>3.2. Testing smart contracts</h4><p>The next more interesting and useful thing about Truffle is that we can test our contracts. This framework lets you write tests in two different ways: Javascript and Solidity. In this post, we will just learn some basics about JS tests, which is the most used option.</p><p>Truffle uses <a href="https://mochajs.org/">Mocha</a> under the hood as the testing framework and <a href="http://chaijs.com/">Chai</a> to perform assertions. It doesn’t matter if you are not familiar with these libraries, both are really straightforward and implement a similar syntax to other testing frameworks. You can also read the official <a href="https://mochajs.org/">Mocha documentation</a> if you want.</p><p>That said, let’s start with our first test case. We’ll need to create a MyToken.js file inside the test folder. Once you have done that, please paste the next chunk of code into it:</p><pre>const MyToken = artifacts.require(&#39;MyToken&#39;)</pre><pre>contract(&#39;MyToken&#39;, accounts =&gt; {</pre><pre>  it(&#39;has a total supply and a creator&#39;, async function () {<br>    const owner = accounts[0]<br>    const myToken = await MyToken.new({ from: owner })</pre><pre>    const creator = await myToken.creator()<br>    const totalSupply = await myToken.totalSupply()</pre><pre>    assert(creator === owner)<br>    assert(totalSupply.eq(10000))<br>  })</pre><pre>})</pre><p>To run Truffle tests you just need to use the command npx truffle test. Again, there is no need to have running a rpc test node in background since Truffle will do that for you.</p><p>As you may have noticed, this is the second time we use artifacts.require() in our code. The first time was to write the MyToken migration, and by now you might be wondering what it means. Artifacts are the result of compiling every contract separately. These will be placed in the build/contracts/ directory relative to your project root. Through artifacts.require() is how we tell Truffle which contract we’d like to interact with. Just provide the name of a contract and get an abstraction to use it. You can read more about Truffle artifacts <a href="http://truffleframework.com/docs/getting_started/migrations#artifacts-require-">here</a>.</p><p>The only important thing left is the contract() function, which is really similar to Mocha’s describe() function. This is how Truffle guarantees a <a href="http://truffleframework.com/docs/getting_started/testing#clean-room-environment">clean-room environment</a>, it will redeploy your contracts to your Ethereum client and provide a list of the available accounts in it every time it gets called. We do not recommend using deployed instances of contracts for tests, though. It’s better to have each test manage their own instances.</p><p>Now that we know some basics about testing with Truffle, let’s add another interesting scenario. We will test token transfers between accounts:</p><pre>it(&#39;allows token transfers&#39;, async function () {<br>  const owner = accounts[0]<br>  const recipient = accounts[1]<br>  const myToken = await MyToken.new({ from: owner })</pre><pre>  await myToken.sendTokens(recipient, 10, { from: owner })</pre><pre>  const ownerBalance = await myToken.balanceOf(owner)<br>  assert(ownerBalance.eq(9990))<br>  const recipientBalance = await myToken.balanceOf(recipient)<br>  assert(recipientBalance.eq(10))<br>})</pre><p>Finally, it would be good to add some other edge cases, but I will leave that to you. You can also see how I finished this mini DApp using Truffle with the rest of the test cases <a href="https://github.com/facuspagnuolo/ethereum-spiking/tree/master/3-using-truffle">here</a>. You’ll see that I just tackled the same features as we did for the app in the previous post. The only thing that changed is that we’re using Truffle to launch a testing node, deploy our contract and add some tests to make sure our contract works the way we expected.</p><h4>3.3. OpenZeppelin</h4><p>If you got here I’m almost sure you’ve heard about <a href="https://openzeppelin.org/">OpenZeppelin</a>. If you haven’t, you just need to know that it is the most used framework that helps you build smart contracts. It is an <a href="https://github.com/OpenZeppelin/zeppelin-solidity">open-source framework</a> that provides reusable smart contracts to build distributed applications, protocols and organizations, reducing the risk of vulnerabilities by using standard, tested and community-reviewed code.</p><p>Given the huge amount of token contracts, the Ethereum community created a token standard called <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md">ERC20</a> two years ago. The idea was to allow DApps and wallets to handle tokens across multiple interfaces and DApps in a common way.</p><p>That said, it is understandable that some of the most used OpenZeppelin contracts are ERC20 implementations. And this is what we are going to do with our MyToken contract as a first step: make it ERC20 compliant. Let’s install the OpenZeppelin framework first, to do so we will need to run:</p><pre>$ npm install zeppelin-solidity</pre><p>Now, take a look at the new implementation we built using some of OpenZeppelin’s contracts:</p><pre>import &#39;zeppelin-solidity/contracts/token/BasicToken.sol&#39;;<br>import &#39;zeppelin-solidity/contracts/ownership/Ownable.sol&#39;;</pre><pre>contract MyToken is BasicToken, Ownable {</pre><pre>  uint256 public constant INITIAL_SUPPLY = 10000;</pre><pre>  function MyToken() {<br>    totalSupply = INITIAL_SUPPLY;<br>    balances[msg.sender] = INITIAL_SUPPLY;<br>  }</pre><pre>}</pre><p>As you can see we have removed a lot of core functionality. Well, we haven’t removed it, we are just delegating that behavior to the OpenZeppelin contracts. This is really useful since we’re reusing secured and audited code, meaning that we have reduced the attack surface of our contracts.</p><p>Moreover, you may have noticed that we’re extending our token contract from two OpenZeppelin contracts: <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.5.0/contracts/ownership/Ownable.sol">Ownable</a> and <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/v1.5.0/contracts/token/BasicToken.sol">BasicToken</a>. Yes, Solidity supports multiple inheritance, and it is really important for you to know that order matters. Unfortunately this is out of the scope of this post, but you can learn more about it <a href="https://solidity.readthedocs.io/en/develop/contracts.html#inheritance">here</a>.</p><p>As we said, we are extending MyToken from Ownable. Let’s take a look at this contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11af2b3cc998b9ef5fb02d5251d63ac0/href">https://medium.com/media/11af2b3cc998b9ef5fb02d5251d63ac0/href</a></iframe><p>Ownable provides three main functionalities:</p><ul><li>It holds a special address we’ll call its &quot;owner&quot;,</li><li>It allows us to transfer the ownership of a contract, and</li><li>It provides a useful onlyOwner modifier that will guarantee that a function can only be called by the owner.</li></ul><p>Pretty useful, isn’t it? On the other hand, we are extending the BasicToken contract too. Let’s see how that one works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29675dceab3a512b5d66a0a804e2f1b3/href">https://medium.com/media/29675dceab3a512b5d66a0a804e2f1b3/href</a></iframe><p>I’m sure you are more familiar with this code. It is basically what we were doing inside MyToken contract. There are some minor differences because we were not following the ERC20 standard in the original version. What we called <a href="https://github.com/facuspagnuolo/ethereum-spiking/blob/master/3-using-truffle/contracts/MyToken.sol#L18-L26">sendTokens</a> here it is just <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer">transfer</a>, which implements pretty much the same behaviour besides triggering the <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer-1">Transfer</a> <a href="https://solidity.readthedocs.io/en/develop/contracts.html#events">event</a>.</p><p>Another important thing is the using SafeMath for uint256 line. SafeMath is a library proposed by OpenZeppelin to do mathematical operations with safety checks. This is another of the most used contracts since it guarantees that math operations don’t overflow.</p><p>OpenZeppelin is a whole world in itself, please take the time to analyze and learn it deeply. You can start by reading and paying careful attention to the security details of the audited and reviewed <a href="https://github.com/OpenZeppelin/zeppelin-solidity">codebase</a>.</p><p>We have learned two amazing tools of the Ethereum world that will definitely make your development easier. Truffle will help you testing and deploying, and OpenZeppelin will help you writing secure smart contracts through an audited codebase.</p><p>Thank you for reading this post, please remember that any question, feedback or suggestions are welcome! If you liked it, stay tuned for the fourth part of this guide, focused on building a real DApp, a token marketplace!</p><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abdd9644d0c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Ethereum Programming, Part 2]]></title>
            <link>https://medium.com/@facuspagnuolo/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bbf15e1a953</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Fri, 17 Nov 2017 00:01:40 GMT</pubDate>
            <atom:updated>2019-02-13T20:55:33.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eui0CctN-e5nvY4xrEVPqA@2x.jpeg" /></figure><p>This is the second part of our Ethereum introduction guide. If you haven’t read <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094">part 1</a>, I highly recommend it to better understand this post.</p><p><em>Enjoy, and please do not hesitate to reach out with questions, corrections or feedback.</em></p><h4>Index</h4><p><strong>1. </strong><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094"><strong>Taking the first steps</strong></a></p><p><strong>2. Interacting with a contract</strong></p><p>2.1. Introduction to smart contracts in Ethereum</p><p>2.2. Your first smart contract</p><p>2.3. Deploying a smart contract</p><p>2.4. Web3 and smart contracts</p><p><strong>3. </strong><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-3-abdd9644d0c2"><strong>Frameworks &amp; Tools in the real world</strong></a></p><p><strong>4. A real DApp, a token marketplace — </strong><em>coming soon</em></p><h3><strong>2. Interacting with a contract</strong></h3><h4>2.1. Introduction to smart contracts in Ethereum</h4><p>Well, you already know some basics about Ethereum, you’ve been interacting with an Ethereum node, sent some transactions between accounts, etc. But there is something else that makes Ethereum amazing: smart contracts.</p><p>As I explained in the introduction, a smart contract is a program that runs on the EVM. You can build any smart contract to do whatever you want, but today, most are being used for crowdfounding tools like <em>ICOs </em>or <em>token sales. </em>Allow me to explain these.</p><p>I will start with <em>crowdfunding, </em>a concept that I’m sure you’re familiar with. Projects do a crowdfunding campaign in order to raise funds to carry out a project. You can issue a digital asset related to your project and immediately sell it to anyone in the world, for almost zero cost. This is what we call an Initial Coin Offering (ICO).</p><p>To carry out an ICO with smart contracts, you just need to implement the logic that makes your digital assets tradable and valuable. Sounds great, doesn’t it? These are <em>Ethereum tokens</em>. A token is a digital asset within the Ethereum ecosystem.</p><p>Let’s try to analyze all these ideas through an example.</p><p>Suppose you have health food company that wants to launch a new brand. You decide to conduct an ICO to raise 20,000 ETH. You offer 10 tokens in return for every 1 ETH you collect, promising that contributors will be able to buy food at your stores with the tokens. To do this, you can develop a token smart contract that stores the proportional amount of tokens for each contributor.</p><p>Now, let’s suppose you raised that money, developed your project, and opened your first store. Then, you decide to sell each salad for 1 token. After a week, it turns out that you have an increasing demand, but given that the supply of salads is limited, your customers notice and start trading your tokens as an asset, raising their market value.</p><p>This process has been carried out in real life, given Ethereum allows virtually anyone to create their own tradeable, digital asset.</p><h4>2.2. Your first smart contract</h4><p>Let’s see how you can build a basic Ethereum token. I will use this example to make an introduction to some Solidity basics.</p><p><em>Please know that this examples are just for learning purposes, you should not use them in production.</em></p><pre>pragma solidity ^0.4.0;</pre><pre>contract MyToken {<br> address public creator;<br> uint256 public totalSupply;<br> mapping (address =&gt; uint256) public balances;</pre><pre>function MyToken() public {<br>   creator = msg.sender;<br>   totalSupply = 10000;<br>   balances[creator] = totalSupply;<br>}</pre><pre> function balanceOf(address owner) public constant returns(uint256){<br>   return balances[owner];<br> }<br> <br> function sendTokens(address receiver, uint256 amount) <br> public returns(bool){<br>   address owner = msg.sender;<br>   <br>   require(amount &gt; 0);<br>   require(balances[owner] &gt;= amount);<br>   <br>   balances[owner] -= amount;<br>   balances[receiver] += amount;<br>   return true;<br> }<br>}</pre><p>Let’s go step by step. The pragma keyword tells which version of Solidity you are using for your source code. Then, it begins the contract definition initiating with its name, in this case, MyToken. Next, you will find three variables:</p><ul><li>creator is an address variable to store the owner of the contract.</li><li>totalSupply is an 256 bit unsigned int to store the amount of tokens willing to be shared with the investors</li><li>balances is a map from addresses to unsigned ints where the balances of each investor will be stored</li></ul><p>Afterwards, you will find the constructor function. As you can see, it is a function with the same name of the contract, and it will be called only once every time a new instance of the contract is deployed to the network. Here is where the owner of the contract gets stored. Since every function call is a transaction, it is possible to know the owner of the contract using the sender of the transaction, that is msg.sender. Finally, the contract defines a total supply of 10,000 tokens, and assigns it to the token creator.</p><p>The next function is an easy one: balanceOf simply tells you the balance of an address received by parameter. Maybe you are wondering what the constant keyword means. Well that’s because Solidity has two kinds of functions, constants and non-constant.</p><p>Non-constant functions perform state changes. On the other hand, constant functions are read only once, meaning those don’t perform any state changes, they just read data. Actually, there are two types of constant functions:</p><ul><li>view declared functions promise not to modify the state (alias to constant)</li><li>pure declared functions promise not to read from or modify the state</li></ul><p>The last function is the one that allows us to trade tokens between addresses. This is a non-constant or transactional function because you will be changing balances. It expects the receiver’s address and the amount of tokens you want to transfer by parameter, and it returns a boolean representing whether the transaction has been successfully executed or not. You can skip the first line, it is just keeping the sender of the function in the owner variable.</p><p>Next, you will find two preconditions:</p><pre>...<br>require(amount &gt; 0);<br>require(balances[owner] &gt;= amount);<br>...</pre><p>require is one of the methods that you can use to check conditions or make validations. It will eval a condition and revert in case that condition is not met. So, in this case, it is requiring that the amount of tokens to be transferred is greater than zero, and ensuring the sender has enough balance to send that amount.</p><p>Finally you are subtracting the required amount of tokens from the owner’s balance and adding it to the receiver’s balance:</p><pre>...<br> balances[owner] -= amount;<br> balances[receiver] += amount;<br> return true;<br>}</pre><h4>2.3. Deploying a smart contract</h4><p>Now, let’s start playing with our contract! You will need to deploy our contract to the network first. To do that, you will use a Solidity compiler for node.js called solc. You can install it by running:</p><pre>npm install -g solc</pre><p>Create a file called MyToken.sol, and paste the contract code into it. Then, open a terminal console in the same dir where you placed that file. First, compile it running the following command:</p><pre>solcjs MyToken.sol --bin</pre><p>The compiler will create a MyToken_sol_MyToken.bin file with the output. You can check that file contains just bytecode. Next, you will need to use solc to build the ABI (Application Binary Interface), an interface or template of your contract that tells you the available methods of it. This is the point of contact with Web3. Your just need to run:</p><pre>solcjs MyToken.sol --abi</pre><p>Then, you will see a new file called MyToken_sol_MyToken.abi with a JSON content that bassically defines the interface of your contract.</p><p>Finally you just need to deploy your contract from a node.js console using testrpc running in background. Once you have done that, let’s initialize web3:</p><pre>//instance web3</pre><pre>Web3 = require(&#39;web3&#39;)<br>provider = new Web3.providers.HttpProvider(&quot;http://localhost:8545&quot;)<br>web3 = new Web3(provider)</pre><p>Web3 gives you the possibility to parse your contract ABI and provide a JavaScript API to interact with it. Then, you just need the bytecode to deploy a new instance of that contract to testrpc. Please follow the next commands:</p><pre>// load files</pre><pre>myTokenABIFile = fs.readFileSync(&#39;MyToken_sol_MyToken.abi&#39;)<br>myTokenABI  = JSON.parse(myTokenABIFile.toString())</pre><pre>myTokenBINFile = fs.readFileSync(&#39;MyToken_sol_MyToken.bin&#39;)<br>myTokenByteCode = myTokenBINFile.toString()</pre><pre>//deploy</pre><pre>account = web3.eth.accounts[0]<br>MyTokenContract = web3.eth.contract(myTokenABI)<br>contractData = { data: myTokenByteCode, from: account, gas: 999999 }<br>deployedContract = MyTokenContract.new(contractData)</pre><p>Finally, you can check the address of your new deployed contract by calling deployedContract.address. Please save that address because you will need it to interact with your contract 😃</p><h4>2.4. Web3 and smart contracts</h4><p>Let’s begin by searching the token balances of your testrpc accounts. To do so, you will need to access the instance of your deployed contract first:</p><pre>contractAddress = deployedContract.address<br>instance = MyTokenContract.at(contractAddress)</pre><pre>web3.eth.accounts.forEach(address =&gt; {<br> tokens = instance.balanceOf.call(address)<br> console.log(address + &quot;: &quot; + tokens)<br>})</pre><p>You will notice that your first account is the one that owns the total supply, which is expected. Great! Next, let’s transfer some of those tokens to another account:</p><pre>// send tokens</pre><pre>amount = 10<br>from = web3.eth.accounts[0]<br>to = web3.eth.accounts[1]<br>transactionHash = instance.sendTokens(to, amount, { from: from })</pre><pre>// checkout balances again</pre><pre>web3.eth.accounts.forEach(address =&gt; {<br> tokens = instance.balanceOf.call(address)<br> console.log(address + &quot;: &quot; + tokens)<br>})</pre><p>You should see that now the second address has 10 tokens! And you can also search for the transaction information as you did in the first part of this guide:</p><pre>web3.eth.getTransaction(transactionHash)</pre><p>I also built a simple UI for this mini DApp, you can find it <a href="https://github.com/facuspagnuolo/ethereum-spiking/tree/master/2-interacting-with-a-contract">here</a>. You will see a MyToken.json file that holds the ABI of our contract. I just pasted the content of the ABI generated by the solidity compiler into it. You will also find an app.js file similar to the previous app, but including the logic that I just showed you to send tokens and detailed token balances of your accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*3m5sRKHnKvQ6LorB." /><figcaption>UI of the DApp that I built to test MyToken transfers</figcaption></figure><p>You can download this app too and start playing with it. You will be asked for the address of the contract instance that you deployed.</p><p>Thank you for reading this post, please remember that any questions, feedback, or suggestions are welcome! If you liked it, stay tuned for the <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-3-abdd9644d0c2">third part of this guide</a>, focused on Ethereum framework and tools.</p><p><strong><em>Note: </em></strong><em>The token described in this article is not ERC20 compliant to reduce the new term overload. If you don’t know what an ERC20 compliant token is, we’ll explain it in the next article.</em></p><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bbf15e1a953" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Ethereum Programming, Part 1]]></title>
            <link>https://medium.com/@facuspagnuolo/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094?source=rss-ecbaaacf79f8------2</link>
            <guid isPermaLink="false">https://medium.com/p/783cc7796094</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[guide]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Facu Spagnuolo]]></dc:creator>
            <pubDate>Tue, 14 Nov 2017 21:58:41 GMT</pubDate>
            <atom:updated>2019-02-13T20:55:46.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jf8dSPrc0wYSje3QdMTOA.jpeg" /></figure><p>Two months ago I was asked to build an Ethereum web application as a work test to join <a href="https://zeppelin.solutions/">Zeppelin</a>, but I didn’t have any idea about blockchain technology at all. I had barely heard of Bitcoin, so there was no other option but to dive in.</p><p>This will be a series of posts aimed at software developers who want to ramp up to Ethereum. Please keep in mind that I do not consider myself an expert in this subject, I’d just like to teach you what I learned and save you some time if you are in the same place I was. By the end of the series you should be able to build a fully-fledged smart-contract-enabled web application (also known as DApp) on your own!</p><p><em>Enjoy, and please do not hesitate to reach out with questions, suggestions or feedback.</em></p><h4><strong>Index</strong></h4><p><strong>1. Taking the first steps</strong></p><p>1.1. Introduction</p><p>1.2. Web3</p><p><strong>2. </strong><a href="https://medium.com/p/7bbf15e1a953?source=linkShare-ecbaaacf79f8-1512215422"><strong>Interacting with a contract</strong></a></p><p><strong>3. </strong><a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-3-abdd9644d0c2"><strong>Frameworks &amp; Tools in the real world</strong></a></p><p><strong>4. A real DApp, a token marketplace — </strong><em>coming soon</em></p><h3>1. <strong>Taking the first steps</strong></h3><h4>1.1. Introduction</h4><p>I’ll assume you have some basic knowledge about computer programming and what a blockchain data structure looks like. If you don’t, please follow <a href="http://www.imponderablethings.com/2013/07/how-bitcoin-works-under-hood.html">this link</a> and come back!</p><p><strong>Ethereum</strong></p><p>Let’s start by defining Ethereum, or at least, what I understood about it after my research. Ethereum is an open-source public platform, distributed and based on blockchain technology, to run applications without censorship or third-party interference.</p><p><strong>Smart Contracts</strong></p><p>Smart contracts are just computer programs. We build Ethereum applications based on smart contracts. Bear in mind that even though this concept comes up with Ethereum these days, it was actually proposed by Nick Szabo in 1996 :)</p><p><strong>Ethereum Virtual Machine</strong></p><p>The EVM is the sandboxed runtime and completely isolated environment for smart contracts in Ethereum. This means every smart contract running inside the EVM has no access to network, file system or other processes.</p><p><strong>Gas</strong></p><p>Given that Ethereum is a distributed platform, there must be a way to limit the resources available to a given smart contract, otherwise it could starve the whole network’s computing power. Gas solves that issue by fixing a cost for every instruction executed in the EVM. One important thing, is that every transaction is sent to the network with a “gas budget”. If it runs out, the transaction will fail but still gets mined into the blockchain.</p><p><strong>Ether (ETH)</strong></p><p>It is the Ethereum cryptocurrency token. There is a gas/Ether dynamic price that measures how much ETH will an operation cost. The fee paid to execute a transaction is calculated by multiplying the gas cost and the gas price (the resulting fee is paid in ETH). You can set the gas price for your transaction to any value. However, if the gas price is too low, no one is going to execute your code.</p><p><strong>Accounts</strong></p><p>Every account is identified by an address. There are two kinds of accounts sharing the same address space. On one hand, we have external accounts controlled by public-private key pairs, commonly owned by people to store ETH. On the other hand, we have contract accounts that are controlled by the code that it’s stored with it. These have a few differences, but one very important to have in mind, is that only external accounts can initiate transactions.</p><p><strong>Transactions</strong></p><p>A transaction is a message sent from one account to another account. You can send a transaction to another external account in order to transfer ETH. If the target account is a contract account, its code will be executed as well. Note that every transaction that involves code execution will be executed on all nodes of the network. Furthermore, every code run, or transaction execution, will be recorded in the Ethereum blockchain.</p><p><strong>Solidity</strong></p><p>Solidity is a contract-oriented high-level language, with similar syntax to JavaScript. It is statically typed, supports inheritance, libraries and complex user-defined types. It compiles to EVM assembly, which is run by the nodes.</p><h4>1.2. Web3</h4><p>I decided to start interacting with the Ethereum blockchain, by first simply sending ETH from one account to another. I didn’t want to do it with real ETH since I was probably going to make a mess, so I started looking for some testing/fake environment. Reading <a href="https://blog.zeppelin.solutions/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05">Manu’s amazing post</a> I found <a href="https://github.com/ethereumjs/testrpc">testrpc</a>, that is a node.js Ethereum client for testing and development. Let’s install it and start playing with it:</p><pre>npm install -g ethereumjs-testrpc</pre><pre>testrpc</pre><p>You will notice that testrpc has generated 10 addresses with fake ETH you can use without the need to worry about them. This is how testrpc works by default, but you can make a custom initialization following the <a href="https://github.com/ethereumjs/testrpc#usage">documentation</a>. It’s important to mention that testrp state is volatile, that is every time you close it, the state of your node and accounts will be cleared.</p><p>The next thing you should get to know is <a href="https://github.com/ethereum/wiki/wiki/JavaScript-API">Web3.js</a>. It is a JavaScript library that implements the Ethereum JSON RPC. That is, the protocol that we will use to talk to an Ethereum node (in this case, testrpc). To install it, just run:</p><pre>npm install -g web3@0.20.1</pre><p>BTW, it is important to install a Web3 0.20.x version, but not the 1.0.0 beta for this exercise. First of all, you need to connect Web3 with your local testing node you are running with testrpc. In order to do that, we will ask Web3 to use a localhost provider. Let’s open a node console and input following lines:</p><pre>Web3 = require(&#39;web3&#39;)</pre><pre>provider = new Web3.providers.HttpProvider(&quot;http://localhost:8545&quot;)<br>web3 = new Web3(provider)</pre><p>Please note that we are using the default testrpc port (8545), if you set another one remember to change the provider URL too. Once you have your web3 instance, start by getting the list of accounts you have in your Ethereum node, with their respective balance, by running the following:</p><pre>web3.eth.accounts.forEach(account =&gt; {<br>  balance = web3.eth.getBalance(account);<br>  console.log(balance);<br>})</pre><p>You probably noticed that the output is not exactly a list of numbers, that’s because Web3 uses BigNumber objects for number values, since JavaScript is not able to handle big numbers correctly. You can read more about this <a href="https://github.com/ethereum/wiki/wiki/JavaScript-API#a-note-on-big-numbers-in-web3js">here</a>.</p><p>You should also know that those balances are not expressed in ETH, actually those are wei values, the base unit. 1 ETH is 10¹⁸ wei. Please follow the <a href="http://ethdocs.org/en/latest/ether.html#denominations">Ethereum documentation</a> to see more about ETH conversions.</p><p>Returning to what we were saying, let’s try to send ETH between two accounts. Just type web3.eth.accounts and pick two of those. Then you can use the sendTransaction method:</p><pre>from = web3.eth.accounts[0]<br>to = web3.eth.accounts[1]<br>transaction = { from: from, to: to, value: 100000 }<br>transactionHash = web3.eth.sendTransaction(transaction)</pre><p>That output is the transaction hash, and you can get the transaction information with it:</p><pre>web3.eth.getTransaction(transactionHash)</pre><p>You may also want to check that the balances of the accounts that you used have changed. You can validate that with the next commands:</p><pre>web3.eth.accounts.forEach(account =&gt; {<br>  balance = web3.eth.getBalance(account);<br>  console.log(balance);<br>})</pre><p>Next, I built a simple UI using HTML and jQuery with a little bit of Bootstrap just to make it pretty. You can take a look at it in my <a href="https://github.com/facuspagnuolo/ethereum-spiking/tree/master/1-interacting-with-the-blockchain">repo</a>. This is what we call a DApp, or decentralised application. That is, an application where part of the backend code runs on a decentralized peer-to-peer network; in this case, the Ethereum network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*paVhmObwXqnaG-gu." /><figcaption>UI of the DApp that I built to test ETH transfers</figcaption></figure><p>You will find an index.html file for the UI, and an app.js file hosting the interaction with the Ethereum node, that is basically what we described above in conjunction with some jQuery callbacks to populate the UI. Please feel free to clone my repo and give it a try.</p><p>Thank you for reading this post, please remember that any question, feedback or suggestions are welcome! If you liked it, stay tuned for the <a href="https://blog.zeppelin.solutions/a-gentle-introduction-to-ethereum-programming-part-2-7bbf15e1a953">second part of this guide</a>, focused on smart contracts!</p><h3>Be part of the community</h3><ul><li>Continue the discussion on our <a href="https://forum.zeppelin.solutions/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">forum</a></li><li>Join our <a href="http://zpl.in/telegram">Telegram group</a></li><li>Follow us on <a href="https://twitter.com/ZeppelinOrg">Twitter</a></li><li>Even better, <a href="https://zeppelin.solutions/jobs/?utm_campaign=zep&amp;utm_medium=blog&amp;utm_source=medium">join the team</a> 🚀</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=783cc7796094" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>