<?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 Jaypee Gee on Medium]]></title>
        <description><![CDATA[Stories by Jaypee Gee on Medium]]></description>
        <link>https://medium.com/@jaypeegee?source=rss-c922f55b3845------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oPE85ssBfXGeaKR77s5jtQ.png</url>
            <title>Stories by Jaypee Gee on Medium</title>
            <link>https://medium.com/@jaypeegee?source=rss-c922f55b3845------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:32:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaypeegee/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[Comment s’affranchir de l’immutabilité d’un Smart Contract ?]]></title>
            <link>https://medium.com/@jaypeegee/comment-saffranchir-de-l-immutabilit%C3%A9-d-un-smart-contract-d4089e886ead?source=rss-c922f55b3845------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4089e886ead</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[french]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Jaypee Gee]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 17:09:57 GMT</pubDate>
            <atom:updated>2020-01-16T12:47:07.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comment s’affranchir de l’immutabilité d’un Smart Contract ?</h3><p><em>NB:</em> This article has been written in French with the kind help of <a href="https://medium.com/u/d70690489838">Léo Besançon</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RT_MhXsmI2cfrJFL" /><figcaption>Photo by <a href="https://unsplash.com/@schnitzler?utm_source=medium&amp;utm_medium=referral">André Schnitzler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>X <em>Le code fourni dans cet article ne peut en aucun cas être utilisé dans un projet réel tel quel. Bien que exécutable il n’a pour ambition que d’illustrer les propos de l’auteur.</em></p><h3>Introduction</h3><p>Malgré tous vos efforts pour créer le Smart Contract parfait, il se pourrait bien que vous ayez besoin de le mettre à jour pour diverses raisons : mise à jour de la logique, bug à éliminer, ajout d’une fonctionnalité, prévention d’un <em>exploit</em>,… Hors l’une des caractéristiques fondamentale et intrinsèque de la technologie blockchain est <strong><em>l’immutabilité</em></strong>, qui empêche a priori toutes possibilités de faire une mise à jour de votre Smart Contract.</p><p>Cependant, en utilisant la bonne technique, vous pouvez déployer la nouvelle version de votre contrat à une nouvelle adresse et rendre l’ancienne version de votre contrat inutilisable.</p><blockquote>Il existe actuellement trois techniques, ou <strong>patterns</strong> en anglais. La technique <strong>Master-Slave</strong> (mise en œuvre très basiquement ci-dessous), la technique Eternal Storage contracts et enfin la technique Upgradable Storage Proxy Contracts.</blockquote><p>Dans ce petit article nous vous proposons d’introduire la mise en oeuvre d’un <em>proxy smart contract, </em>basé sur la technique Maître-Esclave.</p><h3>Introduction aux contrats Maître-Esclave</h3><p>La technique Maître-Esclave est avant tout la technique la plus simple à mettre en œuvre pour pouvoir mettre à jour ses contrats a posteriori.<br>Elle consiste à déployer un contrat Maître qui stocke les adresses des autres contrats et renvoyer une adresse lorsque elle est requise. Les contrats agissent comme des esclaves et récupèrent la dernière adresse d’un contrat en s’adressant au Maître. Pour mettre à jour un contrat il suffit de le déployer sur le réseau et changer l’adresse dans le contrat Maître. Bien que cette technique soit la plus simple elle a aussi ses limites. Notamment nous ne pourront pas migrer les données d’un contrat vers sa nouvelle version (<em>cf.</em> les deux autres techniques citées en introduction de cette article).</p><h4>Delegate call ou comment déléguer l’exécution</h4><p>Le “secret” du fonctionnement d’un <em>proxy contract</em> repose sur l’usage d’une instruction (un <em>opcode</em>) fournit par l’EVM qui se nomme <em>DELEGATECALL</em>. Un DELEGATECALL est comme un CALL normal, excepté que le code de l’adresse cible est exécuté dans le contexte du contrat appelant (<em>i.e.</em> celui qui invoque le DELEGATECALL). Ainsi, lorsque DELEGATECALL est invoqué, le code du contrat cible est exécuté, mais le stockage, l’adresse et les Ethers du contrat appelant sont utilisés. En d’autres termes, DELEGATECALL délégue le contrat cible pour faire tout ce qu’il veut faire avec les ressources (stockage et Ether) du contrat appelant.</p><h3>Description du scénario d’usage</h3><p>Nous allons à présent décrire comment utiliser cette technique sur le scenario suivant. Dans le cadre d’un jeu en ligne nous avons un Smart Contract (Logger) dont le rôle est d’inscrire l’adresse du gagnant dans les logs de la blockchain (parce que stocker des informations dans les logs coûte moins cher en GAS ! 😉). Voici la première version du contrat Logger.</p><pre>pragma solidity &gt;= 0.5.0 &lt;0.6;</pre><pre>contract Logger {<br> event WeHaveAwinner (address);<br> function WeWantToKeepAlogOfTheWinner(address winner) public {<br>   emit WeHaveAwinner(winner);<br> }<br>}</pre><p>Et sans plus attendre, ci-après, la nouvelle version de notre contrat Logger que nous voudrions déployer en remplacement du précédent contrat. L’événement WeHaveAwinner deviendra WeHaveAwinner2. Notez que la modification est mineure à dessein.</p><pre>contract Logger {<br> event WeHaveAwinner2 (address);<br> function WeWantToKeepAlogOfTheWinner(address winner) public {<br>   emit WeHaveAwinner2(winner);<br> }<br>}</pre><p>Enfin, voici le contrat qui gère le jeux, lui aussi réduit au strict minimum pour des raisons de clarté. Il met à disposition une fonction sendEvent() qui appelle la fonction WeWantToKeepAlogOfTheWinner(address) du contrat Logger situé, <strong>semble-t-il</strong> à l’addresse 0xa5a2075… !</p><pre>contract MyGame {<br> Logger public constant logger = <br>        Logger(0xa5a2075994Ca25397B8DAB82e4834C1b09051D57);<br> <br> function sendEvent() public {<br>   logger.WeWantToKeepAlogOfTheWinner(msg.sender);<br> }<br>}</pre><p>Et c’est là que réside l’astuce ! En effet, l’adresse 0xa5a2075… est en fait celle du contrat Maître qui déléguera l’exécution de la fonction WeWantToKeepAlogOfTheWinner() à la dernière version déployée du contrat Logger .</p><h3>Mise en œuvre</h3><p>Le premier contrat qui devra donc être déployé dans un projet est le contrat Maître. Nous avons préféré l’appeler ici LoggerAgent qui est plus adapté dans notre scenario ultra basique. Il contient deux informations essentielles. L’adresse du propriétaire et l’adresse du contrat où Logger est implémenté (déployé). Ces deux adresses sont stockées respectivement dans les deux premier slots (256 bits) de stockage du contrat LoggerAgent, à savoir ownerSlot et implSlot.</p><p>Au déploiement du contrat LoggerAgent, le propriétaire est par défaut la personne qui a déployé ce contrat. Le propriétaire a la possibilité de céder son pouvoir à une autre adresse (EOA ou contrat ?) avec un appel à la fonction setOwner(address).</p><p>On prend soin de noter l’adresse du contrat LoggerAgent,par exemple 0xa5a2075… que l’on insère dans le contrat MyGame.</p><pre>contract MyGame {<br> Logger public constant logger = <br>        Logger(<strong>0xa5a2075</strong>994Ca25397B8DAB82e4834C1b09051D57);<br>...<br>}</pre><p>On peut alors déployer le contrat MyGame. Notez que le déploiement des contrats LoggerAgent et MyGame sont définitifs.</p><p>A présent il est temps de déployer une première version du contrat Logger. Une fois fait, on prend soin de relever son adresse que l’on passera alors en paramètre à la fonction update(address) du contrat LoggerAgent pour mettre à jour son slot implSlot.</p><pre>contract LoggerAgent {</pre><pre> bytes32 private constant ownerSlot = keccak256(“A”);<br> bytes32 private constant implSlot = keccak256(“B”);<br> <br> constructor() public {<br>   setAddress(ownerSlot, msg.sender);<br> }<br> <br> modifier onlyOwner {<br>   require (owner() == msg.sender);<br>   _;<br> }<br> <br> function getAddress (bytes32 _slot) internal view returns (address value) {<br>   bytes32 s = _slot;<br>   assembly {value := sload(s)}<br> }<br> <br> function setAddress (bytes32 _slot, address _address) internal { <br>   bytes32 s = _slot;<br>   assembly {sstore(s, _address)} <br> }<br> <br> function owner() public view returns (address) {<br>   return getAddress(ownerSlot);<br> }<br> <br> function setOwner(address _owner) onlyOwner public {<br>   setAddress(ownerSlot, _owner);<br> }<br> <br> function implementation() public view returns (address) {<br>   return getAddress(implSlot);<br> }<br> <br> function upgrade(address _impl) onlyOwner public {<br>   setAddress(implSlot, _impl);<br> }<br> <br> function _delegateforward(address _impl) internal {<br>   assembly {<br>     calldatacopy(0, 0, calldatasize)<br>     let result := delegatecall(gas, _impl, 0, calldatasize, 0, 0)<br>     returndatacopy(0, 0, returndatasize)<br>     switch result<br>       case 0 {revert(0, returndatasize)}<br>       default {return(0, returndatasize)}<br>   }<br> }</pre><pre> <em># The fallback function</em><br> function () payable external {<br>   _delegateforward(implementation());<br> }<br>} </pre><p>Et voila ! A présent lorsque la fonction WeWantToKeepAlogOfTheWinner() dans le contrat MyGame est appelée, c’est en fait le contrat LoggerAgent qui est sollicité. Celui-ci ne possédant pas de fonction nommée WeWantToKeepAlogOfTheWinner() nous sommes re-dirigé vers la fonction sans nom (la <em>fallback function</em>) qui délègue alors l’exécution au contrat dont l’adresse est stockée dans implSlot, c’est à dire une des versions de Logger introduite au tout début de cet article.</p><p>Vous voulez pousser une mise à jour du contrat Logger ? Pas de problèmes ! Déployez la nouvelle version du contrat Logger, relevez son adresse et faite appel à la fonction update(0xlanouvelleadressedeLogger) du contratLoggerAgent.</p><p>Les appels suivant à WeWantToKeepAlogOfTheWinner()seront bien servis par la nouvelle version de votre Logger.</p><h3>Remarques de fin</h3><p>Pour terminer nous voudrions rappeler que l’utilisation de ce genre de technique peut susciter une certaine méfiance auprès des utilisateurs de contrats dont la logique peut changer n’importe quand sans contrainte. En effet, l’immutabilité est une contrainte pour la programmation certes, mais c’est aussi une caractéristique souvent cherchée !</p><p>Pour rassurer les utilisateurs de ces contrats “proxyfiés” ont peut par exemple avoir recours à un <em>modifier</em> onlyMultiOwner plutôt que seulement onlyOwner. C’est à dire que comme pour un wallet <em>multisig</em>, il faut que <em>n </em>personnes sur les <em>m</em> qui possèdent les droits sur des contrats approuvent le changement d’adresse pour qu’il soit pris en compte.</p><p>Une autre proposition applicable et qui n’exclue absolument pas la précédente est d’autoriser la transmission des appels exclusivement vers des fonctions de signature connues. Cela réduit pas mal d’avantages des proxy puisqu’il faut prévoir tous les types de données qu’on pourrait avoir besoin de passer dans le futur, mais cela peut néanmoins rassurer les utilisateurs.</p><blockquote>Pour en savoir plus !<br>- <a href="https://hackernoon.com/how-to-make-smart-contracts-upgradable-2612e771d5a2">How to make smart contracts upgradable! Hackernoon, September 6th 2018</a><br>- <a href="https://blog.openzeppelin.com/proxy-patterns/">Proxy Patterns, Openzeppelin, April 18th 2018</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4089e886ead" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun with CREATE2]]></title>
            <link>https://medium.com/@jaypeegee/fun-with-create2-70b4b640dd8b?source=rss-c922f55b3845------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b4b640dd8b</guid>
            <category><![CDATA[create2]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Jaypee Gee]]></dc:creator>
            <pubDate>Thu, 07 Nov 2019 18:04:58 GMT</pubDate>
            <atom:updated>2019-11-08T07:42:19.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-authored with <a href="https://medium.com/u/34c49bca363c">pldespaigne</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0pt8asSppPSZr70j" /><figcaption>Photo by <a href="https://unsplash.com/@hellocolor?utm_source=medium&amp;utm_medium=referral">Pawel Nolbert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Since the <em>Canstantinople</em> release of Ethereum (January 2019) a new instruction (or <em>opcode</em>) named create2 is available in the EVM. This instruction is not meant to replace the former create instruction. Their respective goals and usage are different while both allow the deployment of Smart Contracts on an Ethereum blockchain. What distinguishes them from each other is the particular way in which each one calculates the address of the smart contract before deploying it.</p><p>First things first, we need to be clear about few things. Indeed, it is necessary to distinguish <em>DeployCode</em> from <em>RuntimeCode</em>.</p><p><em>DeployCode</em> (sometimes called <em>initCode</em>) is bytecode obtained after compilation of the source code (ex: Solidity) and then before deployment, including constructor’s code and also constructor’s parameter(s).</p><p><em>RuntimeCode</em> is bytecode actually stored in the blockchain after deployment, without the constructor’s code and once the constructor’s code has been executed.</p><blockquote>NB :<em> Remix uses the term </em>Bytecode<em> as a synonym for </em>DeployCode<em> and </em>Runtime<em> </em>Bytecode<em> for the aforementioned </em>RuntimeCode<em>.</em></blockquote><p>Now we can focus on the create and create2 instructions.</p><p>The create instruction requires as input the <em>DeployCode</em> of the smart contract to actually deploy it. create then returns the smart contract addresses computed thanks to the deployer&#39;s address issuer (which can be an EOA or a Smart Contract address) and its <em>nonce</em> (incremented at each transaction).</p><p>The create2 instruction in addition to the smart contract <em>DeployCode</em> as input parameter, requires also a <em>salt</em> (a 256 bits value). The returned address is computed thanks to the current address, the salt and the hash of the <em>DeployCode</em>, and that&#39;s it! In short, nothing we can&#39;t control. Consequently, it means that <strong>a smart contract address can be pre-computed</strong> without the inconvenience of the <em>nonce</em> changing at each transaction.</p><p>Here is the <a href="https://solidity.readthedocs.io/en/develop/assembly.html#opcodes">official</a> definition of the create2 instruction (feel free to skip it), but for a detailed description you can consult the <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1014.md">EIP-1014</a> submitted by <em>Vitalik Buterin</em> himself.</p><blockquote><em>create2(v, p, n, s) create new contract with code </em><em>mem[p…(p+n)) at address </em><em>keccak256(0xff . this . s . keccak256(mem[p…(p+n))) and send </em><em>v wei and return the new address, where </em><em>0xff is a 8 byte value, </em><em>this is the current contract&#39;s address as a 20 byte value and </em><em>s is a big-endian 256-bit value.</em></blockquote><h3>Pre-compute the contract address</h3><p>Let’s have some fun now ! Find below a purposely simple smart contract we called <em>Zombie.sol</em>. This contract comes with a killme() function used to destroy the contract to show later that we can redeploy this same contract at the very same exact address without difficulties.</p><p><strong>Zombie.sol</strong></p><pre>pragma solidity ^0.5.8;</pre><pre>contract <strong>Zombie</strong> {<br>    uint256 public value;<br>    <br>    constructor() public {<br>        value = 1;<br>    }<br>    function <strong>setValue</strong>(uint256 _value) public {<br>        value = _value;<br>    }<br>    function <strong>killme</strong>() public {<br>        selfdestruct(msg.sender);<br>    }<br>}</pre><p>In order to pre-compute the address and later deploy this contract with create2 we will use a &quot;Factory&quot; contract. You can find one on <em>Goerli</em> at <a href="https://goerli.etherscan.io/address/0xebe6eb096f5fdadea6de646b8f0daff6f63f11f7#code"><em>create2.eth</em> (0xebe6...11f7)</a> address. Find below, the source code of the two functions we are going to use, namely computeAddress() and deploy().</p><p><strong>Factory.sol</strong></p><pre>// create2 playground by <a href="http://twitter.com/pldespaigne">@pldespaigne</a><br>// based on contract written by <a href="http://twitter.com/miguelmota">@miguelmota</a> &amp; <a href="http://twitter.com/ricmoo">@ricmoo</a></pre><pre>pragma solidity &gt;0.4.99 &lt;0.6.0;</pre><pre>contract Factory {<br>  event Deployed(address addr, uint256 salt);<br>  <br>  function <strong>computeAddress</strong>(bytes memory code, uint256 salt) public view returns(address) {<br>    uint8 prefix = 0xff;<br>    bytes32 initCodeHash = keccak256(abi.encodePacked(code));<br>    bytes32 hash = keccak256(abi.encodePacked(prefix, address(this), salt, initCodeHash));<br>    return address(uint160(uint256(hash)));<br>  }<br>  <br>  function <strong>deploy</strong>(bytes memory code, uint256 salt) public returns(address) {<br>    address addr;<br>    assembly {<br>      addr := create2(0, add(code, 0x20), mload(code), salt)<br>      if iszero(extcodesize(addr)) {<br>        revert(0, 0)<br>      }<br>    }<br>    emit Deployed(addr, salt);<br>    return addr;<br>  }<br>}</pre><p>For now, we will not explain in detail this source code above.</p><p>The computeAddress() function requires the contract&#39;s <em>DeployCode</em>, so, our first step is to obtain this <em>DeployCode</em> from the <em>Zombie.sol</em> contract. We can use Remix to achieve this. Cut&#39;n paste <em>Zombie.sol</em> source code in the Remix editor, select the right compiler version (0.5.8), launch compilation and copy the produced <em>DeployCode</em>.</p><p>Paste this hexadecimal string starting with 608060405234… in the <em>computeAddress() </em>function of the “Factory” available online <a href="https://goerli.etherscan.io/address/0xebe6eb096f5fdadea6de646b8f0daff6f63f11f7#readContract">here</a>. Do not forget to (1) prefix the string with <strong>0x</strong>, and (2) remove the double quotes.</p><p>Alternatively, you can cut’n paste the string below if you don’t want to mess with Remix.</p><h4>Zombie DeployCode</h4><pre>0x608060405234801561001057600080fd5b50600160008190555061011e806100286000396000f3fe6080604052348015600f57600080fd5b5060043610603c5760003560e01c806324d97a4a1460415780633fa4f24514604957806355241077146065575b600080fd5b60476090565b005b604f60a9565b6040518082815260200191505060405180910390f35b608e60048036036020811015607957600080fd5b810190808035906020019092919050505060af565b005b3373ffffffffffffffffffffffffffffffffffffffff16ff5b60005481565b806000819055507f4eb405514a39e0e076ebb055cbd8c59320e434aa390808e13d45e7f0b61a64506000546040518082815260200191505060405180910390a15056fea165627a7a72305820cde26bd9373cc77db51e3cf3916dfd9fc8a735009013bb5acdac1068f6f4cf930029</pre><p>Below is a snapshot of <a href="https://goerli.etherscan.io/address/0xebe6eb096f5fdadea6de646b8f0daff6f63f11f7#readContract">etherscan.io</a> used here to simplify the interaction with the “Factory” contract. We choose <em>4242</em> as salt value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9DYZkPGBJgmUy63tou-bw.png" /></figure><p>Click the <em>Query</em> button. We obtain an address. If we actually deploy (with the create2 instruction) the Zombie contract, it will be deployed for sure at the said address 0x48f94bc7f6ee9d434630767f8e635438b0672457. Let’s check this !</p><h4>Deploy the contract at the pre-computed address</h4><p>Once again we will use the <a href="https://goerli.etherscan.io/address/0xebe6eb096f5fdadea6de646b8f0daff6f63f11f7#writeContract">“Factory” contract</a> to simplify the deployment procedure by using its deploy() function.</p><p>Because we are now going to change the state of the (Goerli) blockchain, we need some funds and a wallet. We assume in this article that readers know how to use Metamask and obtain some (Goerli) Ether from the <a href="https://goerli-faucet.slock.it/">faucet</a> (<a href="https://goerli-faucet.slock.it/">https://goerli-faucet.slock.it</a>).</p><p>Cut’n paste the same bytecode as above (prefixed by 0x and without double quotes) in the <em>code</em> field and set the <em>salt</em> value with the same value chosen before (<em>i.e.</em> 4242).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*FjwG44RyunucHw7h_Np8mQ.png" /></figure><p>Click the <em>Write</em> button and, this time, accept to pay a fee to actually deploy the Zombie contract (do not forget to connect <em>etherscan.io</em> with <em>Metamask</em>).</p><p>We will now use Remix to interact with the Zombie contract. If not yet done, you will have to paste the <em>Zombie.sol</em> source code, compile it and select <em>Injected Web3</em> at the top left of the Remix interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*Pm8Hpkd76ejPrK9auwcFVQ.png" /></figure><p>Set the pre-computed address (0x48f94bc7f6ee9d434630767f8e635438b0672457) in the <strong><em>At Address</em></strong> field. Immediately after you should be able to interact with the Zombie contract. Feel free to change the value with setValue() function. By default, the constructor of the Smart Contract set value to 1.</p><p>Now destroy the contract by calling <em>selfdestruct</em> instruction via the killme() function, and ask again for the value. It should be reset to zero. The contract has gone !</p><p>Redeploy the contract (with the “Factory’s” deploy() function as seen above). Value is back to one, as stated by the constructor.</p><h3>Constructor with argument</h3><p>Below is another contract called <em>GreedyGreeter.sol</em>.</p><p>This contract says ”Hello World !” when you call greet() if it has at least <em>0.1 Ether</em> on it’s balance, but since it hasn’t any <em>payable</em> function (constructor() function included) you can not send Ether to the contract !</p><h4>GreedyGreeter.sol</h4><pre>pragma solidity ^0.5.8;</pre><pre>contract GreedyGreeter {<br> <br> string message;<br> address payable public recoveryAddress;<br> <br> event MessageSet(string message);<br> <br> constructor(address payable _recoveryAddress) public {<br>   message = “Hello World !”;<br>   recoveryAddress = _recoveryAddress;<br> }<br> <br> function <strong>setMessage</strong>(string memory _newMessage) public {<br>   message = _newMessage;<br>   emit MessageSet(message);<br> }<br> <br> function <strong>greet</strong>() public view returns(string memory) {<br>   require(address(this).balance &gt;= 0.1 ether, “Not enough ether in the contract balance !”);<br>   return message;<br> }<br> <br> function <strong>destroy</strong>() public {<br>   require(msg.sender == recoveryAddress, “You have not the permission to destroy the contract !”);<br>   selfdestruct(recoveryAddress);<br> }<br>}</pre><p>Thus, in order to successfully call greet() you have to :</p><ol><li>Pre-compute the deployment address of the contract</li><li>Send some Ether to this address (at least 0.1 ETH)</li><li>Deploy the contract at the given address thanks to create2</li><li>Call the greet() function on the newly deployed contract</li><li>Finally, you can now call destroy() in order to get back your Ether !</li></ol><p>Notice that there is one more difficulty here. You must set the _recoveryAddress constructor’s parameter at deployment time, then at computeAddress() call time also.</p><p>To do that, take your own Ethereum address, remove the leading 0x and pad it to make it 64 char long (<em>i.e.</em> 24+40).</p><p>Example : 0x4D7e2f3ab055FC5d484d15aD744310dE98dD5Bc3 becomes 0000000000000000000000004D7e2f3ab055FC5d484d15aD744310dE98dD5Bc3</p><p>Then, past this at the end of the <em>GreedyGreeter</em> DeployCode.</p><p><em>NB:</em> All the arguments of the constructor are simply pasted at the end of the DeployCode (<em>cf.</em> <a href="https://solidity.readthedocs.io/en/v0.5.10/miscellaneous.html#layout-of-call-data">documentation</a>).</p><h4>GreedyGreeter DeployCode</h4><pre>0x608060405234801561001057600080fd5b506040516020806107908339810180604052602081101561003057600080fd5b81019080805190602001909291905050506040518060400160405280600d81526020017f48656c6c6f20576f726c642021000000000000000000000000000000000000008152506000908051906020019061008c9291906100d4565b5080600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610179565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061011557805160ff1916838001178555610143565b82800160010185558215610143579182015b82811115610142578251825591602001919060010190610127565b5b5090506101509190610154565b5090565b61017691905b8082111561017257600081600090555060010161015a565b5090565b90565b610608806101886000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c8063368b877214610051578063710eb26c1461010c57806383197ef014610156578063cfae321714610160575b600080fd5b61010a6004803603602081101561006757600080fd5b810190808035906020019064010000000081111561008457600080fd5b82018360208201111561009657600080fd5b803590602001918460018302840111640100000000831117156100b857600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506101e3565b005b6101146102b7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61015e6102dd565b005b6101686103be565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101a857808201518184015260208101905061018d565b50505050905090810190601f1680156101d55780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b80600090805190602001906101f99291906104d8565b507f3d7f415c35b881f2d0a109b3d9a1377e1e14afec5cc1fd06b563ed160c5e2630600060405180806020018281038252838181546001816001161561010002031660029004815260200191508054600181600116156101000203166002900480156102a65780601f1061027b576101008083540402835291602001916102a6565b820191906000526020600020905b81548152906001019060200180831161028957829003601f168201915b50509250505060405180910390a150565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610383576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260358152602001806105a86035913960400191505060405180910390fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b606067016345785d8a00003073ffffffffffffffffffffffffffffffffffffffff16311015610438576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a81526020018061057e602a913960400191505060405180910390fd5b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104ce5780601f106104a3576101008083540402835291602001916104ce565b820191906000526020600020905b8154815290600101906020018083116104b157829003601f168201915b5050505050905090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061051957805160ff1916838001178555610547565b82800160010185558215610547579182015b8281111561054657825182559160200191906001019061052b565b5b5090506105549190610558565b5090565b61057a91905b8082111561057657600081600090555060010161055e565b5090565b9056fe4e6f7420656e6f75676820657468657220696e2074686520636f6e74726163742062616c616e63652021596f752068617665206e6f7420746865207065726d697373696f6e20746f2064657374726f792074686520636f6e74726163742021a165627a7a723058204a6c3a3117b721bb90287d1a91c16a26484076e0f1c92406bcec3db3cc5cef4b0029 &lt;-- your padded address here --&gt;</pre><p>You should obtain a hex string of <strong>3938 chars</strong> ending with your Ethereum address. The 64 char address that you paste at the end of the bytecode corresponds to the _recoveryAddress constructor argument of the GreedyGreeter solidity code above.</p><h4>1) Pre-compute the contract address</h4><ul><li>Go to the Etherscan &gt; Goerli &gt; 0xebe6eb096f5fdadea6de646b8f0daff6f63f11f7 &gt; <em>readContract</em> tab &gt; computeAddress function</li><li>Paste your <em>DeployCode</em> and choose a <em>salt</em> (it has to be a number)</li><li>Click the<em> Query </em>button. The function will return the address of the future contract instance.</li></ul><h4>2) Send Ether to pre-computed address</h4><ul><li>Send at least 0.1 ETH</li></ul><h4>3) Deploy the contract at the given address</h4><ul><li>Go back to the “Factory” contract on Etherscan</li><li>Go to the <em>writeContract</em> tab and click on <em>Connect with MetaMask</em></li><li>Paste your bytecode and the <strong>same</strong> salt as step 1)</li><li>Click on the <em>Write </em>button<em> </em>to deploy the contract.</li></ul><h4>4) Call the greet() function</h4><ul><li>Go to <a href="http://remix.ethereum.org/">Remix</a> (<a href="http://remix.ethereum.org/">http://remix.ethereum.org</a>)</li><li>Copy/Paste the solidity code of the <em>GreedyGreeter.sol</em> in the editor</li><li>Compile it</li><li>Go to the <em>Run</em> tab</li><li>Be sure you selected <em>Injected Web3</em>, then paste the newly deployed contract address and click on <em>At address</em></li><li>call the greet() function !</li></ul><h4>5) Call destroy()</h4><p>You can now call the destroy() function, this will <em>selfdestruct</em> the contract and send you back your Ether !</p><h3>Conclusion</h3><p>Because the create2 address is calculated from the hash of the <em>DeployCode</em>, which therefore includes the arguments of the constructor, then, if the argument(s) change, the contract address will change too. In some cases, it might become a limitation.</p><p>Anyway ! Bravo ! You are now able to pre-compute the address of any smart contract. Even those requiring some parameters for the constructor. As seen, create2 keeps the creation of contract as simple as keys generation. It may solve user adoption difficulties by skipping key pair management issues. Indeed, keys should provide access to funds and not hold the funds.</p><p>For example, you can assign a contract, like a <em>smart wallet</em> contract to thousands of potential customers. At no cost you can now provide them with an address without actually deploying those smart wallets on-chain. If some of these customers finally turn out to be real clients adopting your solution, there will always be time to actually deploy their contract, and pay the Gas only for those early adopters.</p><p>To summarize, as stated in EIP-1014, create2 is intended to solve <em>usability</em> and <em>scalability</em> to simplify <em>Layer2</em> solutions creation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b4b640dd8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good Practices for Ethereum Smart Contracts development]]></title>
            <link>https://medium.com/@jaypeegee/good-practices-for-ethereum-smart-contracts-development-d7395fc1b7ee?source=rss-c922f55b3845------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7395fc1b7ee</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[Jaypee Gee]]></dc:creator>
            <pubDate>Wed, 31 Jul 2019 15:14:52 GMT</pubDate>
            <atom:updated>2019-08-27T10:02:10.629Z</atom:updated>
            <content:encoded><![CDATA[<p>Blockchain technology is the promise of a large number of change in the Internet usage as we know it today. In particular, the <em>Ethereum blockchain</em> is one of the most popular technologies which allows to deploy and make available computing resources rich enough to execute what we call Smart<br>Contracts. However, even the smallest programming error in a Smart Contract may have dramatic consequences. Thus, in this article we focus on the good programming practices of these Smart Contracts by first proposing some reminders on the Ethereum technology and then exposing a set of tools ranging from applying templates to implementing automated tests. Then, we propose a vulnerabilities taxonomy and a set of propositions to optimize the cost of Smart Contract code. <strong>We believe that all these proposals should be known by any intermediate Smart Contract developers.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WhYx_q_K9LoU6EX8" /><figcaption>Photo by <a href="https://unsplash.com/@sadswim?utm_source=medium&amp;utm_medium=referral">ian dooley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>INTRODUCTION</strong></h4><p>Blockchain is an emerging technology which lacks a legal framework, posing legal challenges in terms of legal responsibilities and consumer protection. For the Ethereum blockchain technology, Smart Contracts replace traditional contracts. They are authority-less autonomous programs, that directly control numeric securities (digital assets), based on mutually agreed terms. They look like <em>if-then </em>instructions that automatically evaluate predefined conditions and do transactions.</p><p>A smart contract has an owner and a life cycle, and is executed on the Ethereum Virtual Machine (EVM) running on a blockchain which guarantees that contract terms will not change (immutability characteristic).</p><p>However, this advantage proves to be an inconvenience when a bug is introduced on a smart contract. In fact, unlike traditional contracts they are impossible to challenge.</p><p>Then, before going further about programming Smart Contracts, we provide in the next section some reminders about the current Ethereum network. Next, we focus our attention on the Ethereum Smart Contracts discussing their life cycle. Section titled Good practices, enumerates solutions which should be applied to build Smart Contracts. From using templates to automated testing, through the introduction of several common and freely available tools. Finally, last two sections respectively introduce a taxonomy of vulnerabilities and provide a list of several optimisations to reduce transactions cost each intermediate Smart Contract developer should know.</p><h4><strong>ETHEREUM NETWORK</strong></h4><p>Currently, the Ethereums main network (<em>mainnet</em>) gathers around 9000 nodes according to the <a href="https://www.ethernodes.org/network/1">Ethernode</a> web site monitor. Nodes are deployed throughout the planet, with a large amount in the United States. Each node can:</p><ul><li>Host all, or a part, of the blockchain;</li><li>Mine and validate new blocks;</li><li>Execute smart contracts.</li></ul><p>To execute Smart Contracts, Ethereum nodes run a virtual machine called EVM which stands for Ethereum Virtual Machine. Thus, the Ethereum infrastructure is a huge distributed (<em>quasi-</em>) Turing complete computer system that has the property of being highly fault tolerant due to the enormous<br>redundancy. The executions of these instructions that alter the blockchain take the form of <em>transaction</em> with an associated transaction number, mining and validation operations, and they generate a cost.</p><p>Since a smart contract deployed is strictly identical on all nodes of the network, each of them will produce exactly the same result on all nodes because all the instructions are deterministic. This is why such a large-scale replicated computational infrastructure can guarantee consistency to end-users and also the strict and good code execution.</p><blockquote>In summary, Ethereum offers a decentralized computing system, tamper-proof, always available, accessible from everywhere and by everyone. However it is also a computing system where any action changing its state is not free of charge, and which produces consistent results in the long term.</blockquote><h4><strong>SMART CONTRACT LIFE CYCLE</strong></h4><p>In this section we briefly summarize the life cycle of a smart contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMnwSwQsc27yzE04xMYQvQ.png" /></figure><p>As shown on this figure, the smart contract life cycle follows the steps listed below :</p><ul><li>A Smart contract is implemented using a high level language such as Solidity.</li><li>Smart contract source code is compiled. This generates EVM bytecode and an <em>Application Binary Interface </em>(ABI). ABI is needed to access bytecode. It is the interface that helps other programs communicate with the EVM bytecode including encoding Solidity contract calls for the EVM, thus defining which functions we can invoke.</li><li>The smart contract is then deployed. This consists of creating a transaction packing the smart contract bytecode, and sending it to the network. The transaction gets its own contract account which has an address, a balance, a Nonce, and holds the bytecode in the data field.</li><li>Finally, a Smart contract is invoked. This consists of external calls to the smart contract.</li></ul><p>A smart contract is not self-executable. It requires an external call to be executed. Otherwise, it is pending until someone calls one of its implemented functions. Once it is executed, transactions resulting from the execution are transcribed on the blockchain and eventually smart contracts meta data are updated.<br>Smart contract execution can be launched either by a human with a private key account, also called EOA (Externally Owned Account), or by a Smart Contract account call. In fact, Smart Contracts can interact with each other, however <strong>the first call is always triggered by an EOA account.</strong></p><h4><strong>GOOD PRACTICES</strong></h4><p>Before deploying highly sensitive contracts, dealing with real money on the <em>mainnet</em>, we must build robust and error/bug free contracts.</p><p><strong>A. Smart Contract standards : <em>Build above robust templates</em></strong><br>There are several standards available and used for smart contracts development which are established after the Ethereum Request for Comments (ERC). The most commons are:</p><ul><li>ERC20 which is a standard for the development of tokens on Ethereum describing the behavior of the token by specifying the functions and events an ERC20 token has to handle.</li><li>ERC223 improves ERC20 by integrating a better ”transfer” function and no longer allows token to be transferred to a contract that cannot itself manage the tokens. And finally,</li><li>ERC721 is another standard defined by the Ethereum<br>foundation used to build NFT <em>i.e.</em> Non-Fungible Tokens. While most tokens are fungible (every token is the same as every other token), ERC-721 tokens are all unique, one-of-a-kind collectibles.</li></ul><p>Thus, when the objective is to deploy relatively standard contracts, like a new token (<em>e.g.</em> ERC20/223 or ERC721), we can rely on the expertise of a community of experts in contracts auditing. For example, the <a href="https://openzeppelin.com/contracts/">OpenZeppelin</a> project, maintained by the Zeppelin company, proposes to reduce the risk of vulnerabilities in the applications by using standard, tested and community-reviewed code. Building a contract above their contributions is relatively easy and straightforward, actually. For example, if we want to propose a new NFT (Non Fungible Token) mintable token, we just need to install the <em>openzeppelin-solidity</em> package via the `npm install` command, then import the required modules in our solidity code.</p><pre>pragma solidity ^0.5.0;<br>import &#39;openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol&#39;;<br>import &#39;openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol&#39;;</pre><pre>contract MyNFT is ERC721Full, ERC721Mintable {<br>  constructor() ERC721Full(&quot;MyNFT&quot;, &quot;MNFT&quot;) public {}<br>}</pre><p>Above is the full source code (5–7 <em>sloc</em>) of a Smart Contract proposing a new token called <em>MyNFT</em> (symbol <em>MNFT</em>) which may be deployed safely on the <em>mainnet</em>.<br>Another useful library is <a href="https://github.com/OpenZeppelin/openzeppelin-%20solidity/blob/master/contracts/math/SafeMath.sol">SafeMath</a>, proposed by OpenZeppelin also. It prevents overflow or underflow efficiently which happens when an arithmetic operation reaches the maximum or minimum size of the type. They encourage use of this library to protect from inputs which may lead to unexpected behavior of the contract.</p><p><strong>B. Code review</strong><br>Code review is very important while dealing with smart contracts. Their immutability characteristic may have a dramatic impact especially when a smart contract is deployed with a bug. This happened for <em>TheDAO</em>, a Decentralized Autonomous Organization, where a bug engendered a loss of 3.6 millions Ethers, which were equivalent to 50 millions dollars, that were<br>transferred to an autonomous contract. This demonstrates the importance of code review in that context. Code review goes through some best practices such as a peer code review.</p><p>On the other hand, while using smart contract that needs to access a given data in the blockchain, it is necessary to point to that data in a dynamic way instead of a static way, in order to be able to update the data value when necessary.</p><p>Another good practice consists of allowing smart contract termination in case a bug or vulnerability is discovered, or because the smart contract becomes obsolete. However, this may lead to suspicion on the part of the users. Indeed, the contract could disappear surreptitiously.</p><p><strong>C. Tools box</strong><br>In the next three sub-sections we introduce three tools we use on a daily basis : Metamask, Remix and Truffle.</p><ul><li><strong>Metamask:</strong> Where and how can we keep track and show that we are in possession of some Ether ? Metamask takes the form of a JavaScript extension in our internet browsers (Firefox, Chrome, Opera and Brave are supported) that allows connection to an Ethereum node. It allows us to easily manage our Ethereum accounts and access the different Ethereum networks, including the <em>mainnet</em>. It also allows us to connect to a private Ethereum network we could host on our own machine, using for example <a href="https://truffleframework.com/docs/ganache/quickstart">Ganache</a> tool, by simply specifying the access URL, for example <a href="http://localhost:8545/"><em>http://localhost:8545</em></a>.<br>A decentralized Ethereum application, called <em>Dapps</em>, works directly in our Internet browser. It allows websites to recover data from the blockchain. Metamask manages our private key and then permits a Dapp to change the blockchain state. An alternative to Metamask is the Ethereum Wallet Browser (also called <em>Mist</em>), which allows to connect to testnets or the mainnet. It also allows Smart Contracts to be deployed.<br>Now let’s see two tools which help to write Smart Contracts in Solidity but also enable their deployment and online testing.</li><li><strong>Remix :</strong> <a href="http://remix.ethereum.org/">Remix</a> is a browser-based development environment. It allows us to write Smart contracts in the Solidity language (or Vyper via a plugin), then compile, deploy and even interact with them. Deployment can be done locally in a JavaScript EVM, or over some <em>testnet</em> or even the <em>mainnet</em> via Metamask (accessible through <a href="https://infura.io/">Infura</a> services). And why not locally with Ganache. In the snapshot below we can see the (old) Remix interface used to deploy a Smart Contract and then access all the public functions available in the Smart Contract (wrote in Solidity).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dzb5VxgRo_yT87-hUl60CA.png" /><figcaption>Remix tool available online to easily compile, deploy and test a Solidity Smart contract (old interface).</figcaption></figure><p>At the bottom right, there are functions with a “salmon” background (see <em>setMessage</em> button). When we use them we will have to pay a fee because they change the blockchain state. A blue background function does not affect the blockchain state, then they are free of charge (see <em>getMessage</em> button). <br>Remix is undoubtedly a very handy tool to quickly develop, deploy, test and even debug our Smart Contracts. It is currently the only one tool providing a step-by-step debugger on the EVM.</p><p>However, for important projects in terms of size and use, some programmers will prefer tools provided by the Truffle suite introduced hereafter.</p><ul><li><strong>Truffle:</strong> <a href="https://github.com/trufflesuite/truffle">Truffle</a> provides a complete development environment and test tools for developing Smart Contracts. Truffle is meant to make life easier for developers. It is a tool written in nodeJS, so installable via the `npm install -g truffle` command, which allows to initiate the creation of a new project via the `truffle init` command, and thus obtain bits of blank code, easily compiled via `solc` (the Solidity compiler) by calling the `truffle compile` command, facilitating the deployment (`truffle migrate`), and finally setting up some automated test (`truffle test`) introduced in the next section.</li></ul><p>In summary, Truffle offers: Built-in smart contract compilation, linking, deployment and binary management; Automated contract testing; Configurable build pipeline with support for custom build processes; Scriptable deployment and migrations framework; Network management for deploying to many public or private networks; Interactive console for direct contract communication; Instant rebuilding of assets during development; External script runner that executes scripts within a Truffle environment.</p><blockquote>In conclusion, Truffle and Remix both provide the ability to test and deploy Smart Contracts, but Truffle can be added to a project as a build dependency. For a first experience, we prefer using Remix. It provides a very practical editor and debugger.</blockquote><p><strong>D. Automated testing <br></strong>In addition to code review, a test phase has to be set up. This can be done using a testing blockchain like <a href="https://www.trufflesuite.com/ganache">Ganache</a>, for operating the smart contract. It allows us to evaluate the cost of the smart contract execution, since the latter has an impact on its use. However it might be cumbersome when done repeatedly.</p><p>Automated testing run software programs by executing test cases automatically and produce test results without any human intervention. Automated tests can be run any number of times to test the same application thus minimizing redundant manual work. Thus, automated testing is a ”must” in today software engineering.</p><p>In our context it may help to ensure that :</p><ul><li>Smart Contracts compiles,</li><li>functions of contracts can be called, and</li><li>the logic is stable.</li></ul><p>The Truffle framework, introduced above, relies on the <em>Mocha </em>testing framework as well as the <em>Chai</em> assertion library. Both are very commonly used by JavaScript developers. Listing below shows a JavaScript code used to test two properties of our Hello contract (source code is available on Remix snapshot above).</p><p>The first test check if the default message used when we deployed the contract is still here. The second test proposes to change the string message to another and check after while that the new message is effectively stored in the blockchain.</p><p>All those instructions are executed asynchronously, using JavaScript <em>Promises</em> here, this is why it may be difficult to read this code for non accustomed developers. More specifically in our context, Truffle provides a function called `contract()` which is similar to the `describe()` function in <em>Mocha</em>. However, Truffle adds some features for testing Smart Contracts. For example, it makes sure contract is deployed before running the tests and provide a list of funded accounts. During test, the first account is always chosen by default.</p><pre>const Hello = artifacts.require(&quot;Hello&quot;);</pre><pre>const dfltMessage = &#39;Default message&#39;;<br>const newMessage = &#39;Nouveau&#39;;</pre><pre>contract(&quot;Hello&quot;, accounts =&gt; {</pre><pre>it(`should return \${dfltMessage}`, () =&gt;<br>        Hello.deployed()<br>        .then(instance =&gt; instance.getMessage())<br>        .then(message =&gt; {<br>          assert.equal(<br>            message,<br>            dfltMessage,<br>            `The message is not set to \${dfltMessage}`<br>          );<br>        })<br>        );</pre><pre>it(`should change message to &#39;\${newMessage}&#39;`, () =&gt; {<br>                let meta;<br>                return Hello.deployed()<br>                .then(instance =&gt; {<br>                  meta = instance<br>                  return meta.setMessage(newMessage)<br>                })<br>                .then(() =&gt; meta.getMessage())<br>                .then(message =&gt; {<br>                  assert.equal(<br>                    message,<br>                    newMessage,<br>                    &quot;The message has not changed&quot;<br>                  );<br>                })<br>        });<br>});</pre><h4><strong>TAXONOMY OF THE VULNERABILITIES</strong></h4><p>In [1] and [2] authors analyse in depth the security vulnerabilities of smart contracts providing a taxonomy of common programming pitfalls which may lead to vulnerabilities. These vulnerabilities make enable an adversary to cause huge damage (<em>e.g.</em> stealing tokens from contracts), this is why smart contract developers must know and understand them to audit their code before deployment on the <em>mainnet</em>. Below we propose a brief introduction to each known vulnerability. Most of them have been exploited in the past.</p><ol><li><strong>Call to the unknown</strong>: If the function called by a contract does not exist, the fallback function is triggered. This may happen with the `call` command but also with the `send`or `delegatecall` commands.</li><li><strong>Exception disorder</strong>: An exception may be raised in several circumstances. For example the execution runs out of Gas or the throw command is executed. When a call fail the state may revert to its initial state or in between according to the sequence of calls passed.</li><li><strong>Gasless send</strong>: Sending Ethers may seems inexpensive, but if the recipient fallback function is not empty it will probably fail because 2,300 units of Gas only are allocated to a send command by default.</li><li><strong>Type casts</strong>: In case of type mismatch no exception is thrown, and the caller is unaware of the error.</li><li><strong>Reentrancy</strong>: It is perhaps one of the most infamous flaws with the DAO Attack which cause a huge ether loss in June 2016. The fallback mechanism may allow an attacker to re-enter the caller function and then conduct to unexpected behavior, like a loop to drain all the value holds by the victim contract.</li><li><strong>Keeping secrets</strong>: A field can be declared private in a contract. It just means it is not directly readable by others. Since the blockchain is public, everyone can inspect its content and then infer the value of the field.</li><li><strong>Immutable bugs</strong>: This property of immutability becomes a problem when a contract is published on the blockchain with a bug. There is no way to patch it. The only way to fix it is to make a hard-fork to nullify the transaction which is against the ”code-is-law” principle.</li><li><strong>Ether lost in transfer</strong>: Most addresses are not associated to any user or contract. If a transaction is sent to an orphan address, its value will be lost forever and there is no way to recover it.</li><li><strong>Unpredictable state</strong>: Contract state is determined by the value of its fields and its balance. However, users’ transactions are not guaranteed to be mined sequentially. Moreover, miners may choose to include or not transactions in blocks or when two minors find a valid block a soft fork happens until the longest branch win. Then, transactions in the shortest branch will be abandoned.</li><li><strong>Generating randomness</strong>: All miners executing one transaction will have the same result because the EVM execution is deterministic. Miners have access to all the informations the contract may use to build some entropy and bias the outcome of the pseudo-random generator. Thus, it is a real<br>challenge for a contract to draw a random number, not to say impossible without the involvement of the participants for example.</li><li><strong>Time constraints</strong>: To determine time a contract will use the block timestamps agreed by all miners. However a miner may slightly choose a suitable timestamp of a block he is mining and which holds transaction of interest for him.</li></ol><p>In conclusion, usage of some instructions like <em>call</em> and <em>delegatecall</em> is discouraged and must be avoided as much as possible. While the EVM execution is deterministic as we see above some situations can conduct to indeterminate scenario, although insufficient to build a good random number generator of course. Finally, we strongly recommend to read the document written by <a href="https://medium.com/%20//consensys.github.io/smart-contract-best-practices/recommendations/">Consensys</a> before deploying a Smart contract on the <em>mainnet</em>.</p><h4><strong>OPTIMISATIONS OF TRANSACTIONS COST</strong></h4><p>Each line of code in a smart contract consumes <em>Gas</em>. According to the operation and function used this Gas consumption can increase greatly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dw9ShPt1HgXaTd6_PsJqeA.png" /></figure><p><strong>Table I list Gas costs of some functions and Table II shows the cost of some operations.</strong></p><p>The Gas cost list of all the operations and functions are available in the <em>Ethereum Yellow paper</em> and are regularly updated. Transaction fees are generated during a smart contract execution.</p><p>Gas is the fundamental network cost unit. It is paid exclusively with Ether, which is converted freely to and from Gas as required. Gas does not exist outside of the internal Ethereum computation engine ; its price is set by the transaction and miners are free to ignore transactions whose Gas price is too low.</p><p>The Gas operating is similar to the use of Kilowatt for measuring electricity consumption. The main difference is the fact that the price of Gas is set by the creator of the transaction (in Gwei) and the miner can postpone, refuse or accept this transaction depending on the Gas price set. There is a limit for each block in an Ethereum blockchain and if we want to include our transaction in the next block we need to pay more to increase probability miners include our transaction in the next block.</p><p>The idea to set a price for each transaction is mainly to avoid unwanted infinite loops. Each operation consumes Gas. If the account does not hold enough Ether the transaction will fail or stop. Hence, the goal is to</p><ul><li>stop attacks with infinite loops,</li><li>promote the efficiency in the code and</li><li>force the attacker to pay for the resources used.</li></ul><p><em>Gas limit</em> corresponds to the maximum of Gas that we are willing to spend on a transaction. This excludes the cases where it is possible to find an error somewhere in the contract. For a transaction, the necessary Gas is defined by the cost and number of each instructions of code executed on the blockchain.</p><p>Decrease the amount of <em>Gas limit</em> will not help us to validate our transaction. We need to send enough Gas in order to consider all computational resources that we will use otherwise our transaction could fail with an <em>Out of Gas Error</em>. The total cost of a transaction is called <em>Tx fee</em> and is defined by the product of total Gas used by <em>Gas price</em>. This is not received by service provider but it is paid to miners for the computation, mining transaction and putting transactions into blocks in order to secure the blockchain.</p><p>Setting a high <em>Gas Price</em> value encourage miners to include a transaction in a block. Generally, miners use a basic strategy to include transactions in a block which consists of sorting transactions from highest to lowest <em>Gas price</em>, then add transactions until the block becomes full.</p><p>Like people designing embedded system whose main goal is to reduce memory footprint of their product device, <strong>people designing Smart Contracts must reduce transactions cost as much as possible.</strong></p><ol><li><strong>Data type</strong>: It may seem counter intuitive at first but the best type developers should use for their variables is int256 (or uint256 or bytes32). The EVM use 256 bits (pseudo)-registers, then when we use variables smaller than 256 bits (ex: uint8), the system as to pad it with 0 which cost Gas. Moreover, for calculations, data must be converted.</li><li><strong>Packing variables</strong>: In order to reduce the number of call to the most expansive operation, <em>i.e.</em> SSTORE (20,000 Gas), we may rearrange and pack different variables in the same slot of 256 bits. This can be achieved by using a struct declaration and accessing fields of this struct afterwards.</li><li><strong>Storing constant</strong>: in the bytecode of the Contract whenever it is possible, using the constant declaration. This way it avoid a call to the SLOAD instruction which cost 200 Gas per words.</li><li><strong>Off-chain data storage</strong>: IPFS (or Swarm as an alternative) is a decentralized data storage where files are identified with the <em>hash</em> of their content. This bring two interesting properties. First, the file can not be corrupted, otherwise we will know it, and the hash will always point to the same file. Thus, once the file has been deployed in the IPFS infrastructure, its hash, also used as reference in IPFS, can be stored in the Contract to reference the file. This approach suits particularly well to store large datasets, however the contract can not easily access or alter the data stored in the file.</li></ol><blockquote>In conclusion, we introduced above some simple optimisations and ideas to reduce Gas consumption of a Contract.</blockquote><h4><strong>CONCLUSION</strong></h4><p>Build efficient and robust Smart Contracts is a real challenge. Especially when it is based on technologies still in their infancy and then subject to change. As contracts become more complex and mission critical, these best practices become very difficult to enforce.</p><p>Then, our recommended strategy is to rely on audited Smart contracts code like those provided by OpenZeppelin project whenever possible. Otherwise, all the good practice in software development applies, such as :</p><ul><li>Writing simple and modular code,</li><li>functions should be as short as possible,</li><li>reducing to the minimum code dependencies, and</li><li>files should be as small as possible,</li><li>separating independent logic into modules, each with a single responsibility.</li></ul><p>Based on our experience we present tools used to develop and test contracts at different scale (locally or on some <em>testnet</em>). We also introduced automated test of contracts which is a must in a industrial context.</p><p>Finally, we exposed all known vulnerabilities which have been abused in the past and we introduced briefly several optimisations to reduce transaction cost.</p><h4>REFERENCES</h4><p>[1] Security Vulnerabilities in Ethereum Smart Contracts. Mariusz<br>Nowostawski and Ardit Dika. IEEE Blockchain 2018, Halifax, Canada.<br>[2] “A survey of attacks on Ethereum smart contracts”, Nicola Atzei and<br>Massimo Bartoletti and Tiziana Cimoli. <a href="https://eprint.iacr.org/2016/1007">https://eprint.iacr.org/2016/1007</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7395fc1b7ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>