<?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[OLI Systems - Medium]]></title>
        <description><![CDATA[Rethinking the Energiewende - Medium]]></description>
        <link>https://medium.com/oli-systems?source=rss----9322226ecf04---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>OLI Systems - Medium</title>
            <link>https://medium.com/oli-systems?source=rss----9322226ecf04---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:39:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/oli-systems" 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 Fractionalized Ownership of Distributed Energy Resources on Distributed Ledger…]]></title>
            <link>https://medium.com/oli-systems/introducing-fractionalized-ownership-of-distributed-energy-resources-on-distributed-ledger-2c20b59fb16c?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c20b59fb16c</guid>
            <category><![CDATA[distributed-energy]]></category>
            <category><![CDATA[fractional-ownership]]></category>
            <category><![CDATA[distributed-ledger-tech]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[renewable-energy]]></category>
            <dc:creator><![CDATA[Saikesh Erramshetty]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 07:10:31 GMT</pubDate>
            <atom:updated>2022-06-20T07:52:53.853Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introducing Fractionalized Ownership of Distributed Energy Resources on Distributed Ledger Technology</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMhgn4G_gnjSLIq64xoYpA.jpeg" /></figure><blockquote>With the continuous increase in global energy demand and the scarcity and environmental impact of conventional energy sources, there is a need for more <a href="https://medium.com/ieee-mec-sb/distributed-energy-resources-8dee35bef67b">Distributed Energy Resources</a> (DER), particularly more Renewable Energy Sources for the current and future energy ecosystem. There is also a need for a technological solution that acts in a decentralized manner to manage and support these new energy resources. In this context, <a href="https://medium.com/coinmonks/distributed-ledger-technology-855cbdc28370">Distributed Ledger Technology</a> (DLT) which offers a transparent, immutable, and decentralized network needs to be evaluated.</blockquote><p>Scaling DERs cannot be achieved by a single community, but requires the participation of all citizens. If everyone participates in investing in and owning a portion of some form of renewable energy asset, it will not only help scale green power, but also promote ownership of energy assets as valuable investments and enable new business models for energy assets.</p><p><strong><em>What is Fractionalized Ownership?</em></strong></p><p><strong>Fractionalized ownership</strong> refers to a form of ownership in which the most valuable and infrequently used tangible and intangible assets are acquired and used together, rather than large stakeholders controlling everything. These assets are typically managed by a third party and often established by a property owner or developer who ensures that the rules of use are followed, which all fractional owners agreed to before purchasing the property. This third party also creates a legal framework and documents all requirements.</p><p><strong><em>Applications of Fractionalized Ownership</em></strong></p><p>Applications range from expensive assets like airplanes, sports cars, and vacation properties to real estate, luxury goods, cars, art, large machines, and even cryptocurrencies like Bitcoin and Ethereum that exist in fractional ownership.</p><p>DERs such as PV systems, wind turbines, and storage systems have long existed as fractional ownership models, but to address some of the issues around accessibility to all individuals and the need for transparency for this system, blockchain technology is being introduced to this concept.</p><p><strong><em>Benefits of fractionalized ownership in DLT adoption</em></strong></p><ul><li>Diversification of risks associated with investments.</li><li>Lower acquisition and operating costs.</li><li>Ordinary people can easily acquire such inaccessible assets.</li><li>Elimination of excessive administrative and legal costs.</li><li>DLT enables trust between fractional owners through its immutable, secure, and transparent nature.</li><li>Any movement of asset transfers can also be tracked across secondary markets.</li></ul><p><strong><em>What can be achieved with this concept</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31ItAZAaLKSd9Q4RiiBTZw.png" /></figure><p>Acceptance — In Europe, especially in Germany, there is a major problem with citizen acceptance of renewables. A recent survey by Agentur für Erneuerbare Energien (AEE) found on overall, 55 percent of those surveyed find a renewable energy system in their neighborhood, which is defined as a radius of five kilometers from their own place of residence, very important or rather important. Among renewables, photovoltaics continue to enjoy the greatest acceptance. 59 percent of respondents welcome a solar park in their neighborhood and 77 percent welcome rooftop photovoltaic systems. These values ​​increase significantly by another 13 percent, if the respondents have appropriate facilities.Only 39 percent of respondents tend to like a wind turbine in their neighborhood and these value could increase to 51 percent. For biogas plants, the outcome is 26 percent and another 23 percent can be added. It looks a little better for geothermal systems with 30 percent of those surveyed approved to this and with their own experiences doubling the value. [1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*XJYHKFef9Rc9IUMknYuP2g.png" /><figcaption>AEE Survey for approval of renewables</figcaption></figure><p>AEE survey shows, people’s financial involvement drives approval. Although 48 percent of respondents said it has no influence on their attitude, for 9 percent it definitely drives acceptance, and for 16 percent it tends to. More than a quarter of respondents, however, did not provide any information. This could also be due to the fact that they know little about these participation models. [1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*OIG81TtA4SKOkr9Y0kK_FQ.png" /><figcaption>AEE Survey with citizens financial involvement on renewables</figcaption></figure><p>Many citizens apparently also want to be involved in the planning of renewable plants. Acceptance would then increase for a total of 36 percent of respondents [1]. In view of the results, we must continue to work on citizen involvement and participation models.</p><p>Accessibility — Everyone can have an access to such useful resources effortlessly. For example, people who are interested in owning DERS but cannot afford the high initial investment, or people who do not have their own roof or open space to run their own renewable energy system, can participate and contribute to the energy transition.</p><p>Accumulate — Fractional owners can accumulate their own green electricity and earn returns using these investments while offsetting their carbon footprint.</p><p>Taken together, these three benefits of this concept help to turn electricity consumers into prosumers and increase the share of renewable energy.</p><p><strong><em>Impact assessment example when individual citizens are involved in Renewables</em></strong></p><blockquote>Considering Germany’s population in 2020, which is 83,783,942 people according to UN data statistics and is equivalent to 1.07% of the total world population [2]. If 10% of them (like 8,400,000) own a share of at least 1 kWp then an extra 8.4 GW capacity of new renewable energy sources can be installed each year. Which can generate 8.4 TWh of electricity per year (considering an average kWp generating 1000 kWh of electricity per year).</blockquote><blockquote>Then the share of Renewable sources in the German energy sector which is 247.01 TWh (50.5%) out of 488.7 TWh can be increased by another 2% alongside reducing 1 million tons of carbon emissions per year [3]. So, by converting to such energy sources, we can eliminate Scope 2 emissions (which cover indirect emissions from purchased energy) and significantly decrease the overall carbon footprint prior to compensation [4]. That’s the reason, why renewable technology and its increase is such an important factor in our climate action plan.</blockquote><p><strong><em>Conclusion</em></strong></p><p>Using distributed ledger technology instead of a traditional centralized ledger gives all the fractional owners easy access and control of all asset-related information and transactions which promotes transparency. Also, this concept enables the ownership of such resources to be distributed among small-scale investors instead of being driven by top-down decision-making hierarchies. DLT also reduces the transaction time to minutes and is handled 24/7 without any interruptions.</p><p><strong><em>References</em></strong></p><p>[1] PV-magazine, “AEE acceptance survey: Nothing beats photovoltaic roof systems,” 2021. [<a href="https://www.pv-magazine.de/2021/12/14/aee-akzeptanzumfrage-nichts-geht-ueber-photovoltaik-dachanlagen/?utm_source=dlvr.it&amp;utm_medium=linkedin">Online</a>]</p><p>[2] Worldometers, “world-population and germany-population,” 2021. [<a href="https://www.worldometers.info/">Online</a>]</p><p>[3] D. B. Burger, “Public Net Electricity Generation in Germany 2020: Share from Renewables Exceeds 50 percent,” Fraunhofer ISE, 2021. [<a href="https://www.ise.fraunhofer.de/en/press-media/news/2020/public-net-electricity-generation-in-germany-2020-share-from-renewables-exceeds-50-percent.html">Online</a>]</p><p>[4] ClimatePartner, “Climate Action Insights: An Introduction To Green Energy,” 9 July 2021. [<a href="https://www.climatepartner.com/en/climate-action-insights/how-switching-renewable-energy-will-reduce-your-companys-carbon-footprint">Online</a>]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c20b59fb16c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/introducing-fractionalized-ownership-of-distributed-energy-resources-on-distributed-ledger-2c20b59fb16c">Introducing Fractionalized Ownership of Distributed Energy Resources on Distributed Ledger…</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Todo App Tutorial]]></title>
            <link>https://medium.com/oli-systems/react-todo-app-tutorial-e935fe716179?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/e935fe716179</guid>
            <category><![CDATA[to-do-list]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 16:00:43 GMT</pubDate>
            <atom:updated>2022-06-03T10:09:39.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>BUILDING A TODO APP WITH REACT</h4><h4>A ReactJS Tutorial for Building Awesome Todo App</h4><p>In this post, I’ll explain how to create a Todo app using React (a JavaScript library for building user interfaces), with ES6 syntax and React hooks from scratch. This will be a very basic app, with an input field for inputting the Todo item and a delete button next to each item to delete the item. Additionally, we will use the useState hook from React to preserve the state of our application and some advanced JavaScript features such as map() , arrayspread, ternary operator and filter()methods. The goal of this tutorial is to assist you in getting started with React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*d_QwfmfvmhjuMRS1s9RozQ.gif" /><figcaption>Demo of React Todo App</figcaption></figure><p>The complete project code can be found <a href="https://github.com/m-yahya/react-todo-app">here</a>.</p><h3>Prerequisites</h3><p>Please make sure to have the following installed:</p><ul><li>NodeJS and NPM — <a href="https://nodejs.org/en/download/">Download page</a></li><li>Create React App — <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">Installation guide</a></li></ul><h3>Setup</h3><p>The first step is to create a new React app using thecreate-react-app command-line tool. We will create a new directory and then create a React app inside the newly-created directory. You may the following commands to accomplish this task.</p><pre>1 $ mkdir react-todo-app<br>2 $ cd react-todo-app<br>3 $ create-react-app ./</pre><p>To get started from the scratch, let’s remove everything from the src folder except App.js and index.js files. Inside the App.js , remove everything except the parent heading and add an h1element to it &lt;h1&gt; React Todo App &lt;/h1&gt; . To see your app in action, run npm startin the terminal window at the root of your project.</p><p><a href="https://github.com/m-yahya/react-todo-app/tree/085ae32b891ba29fde943179a83a17409ea2c8aa">This</a> GitHub commit reflects the changes till this point.</p><h3>CSS and Style</h3><p>So far, we have created a very basic app that contains only one h1 element. But before moving on, let’s give our app some basic styles to make it appear great. Create a fileApp.css in the src directory and import it into the App.js file. Add the styles from <a href="https://gist.github.com/m-yahya/55aca7d33f21bb5ae590bb64e2d30e72">this</a> gist to the App.css file.</p><p>You can compare your project with <a href="https://github.com/m-yahya/react-todo-app/tree/770dd4b58d93bd6fc9d0210d12c4edc96329588a">this</a> GitHub commit.</p><h3>Creating the Initial Mockup</h3><p>We will start with a simple mockup that has an input field and a button for adding a new Todo item. In the App.js file, create a new div with the class input-wrapper within the parent div .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*To7K3HfpoFpi6gUEo-nnVw.png" /><figcaption>Create the initial app UI</figcaption></figure><h3>Create and Display Todos</h3><p>This section consists of the following steps:</p><h4>1. Create a New Todo Item</h4><p>To maintain track of the state inside the React component, we’ll use the useStatehook. The useStatehook takes a state’s initial value and returns an array with two values: the first is a getter function that displays the defined state’s current value, and the second is a setter function that updates the state.</p><p>We’ll utilize useStatein this app to keep track of every new Todo item and Todo list. But first, inside the App.jsfile, we’ll import the useStatehook as follows:</p><pre>import { useState } from &quot;react&quot;;</pre><p>To begin, we’ll create a todostate (getter) with an undefinedvalue and a setTodo(setter) method to set the current todoitem’s value:</p><pre>const [todo, setTodo] = useState(&quot;&quot;);</pre><p>The input fields have an onChangeevent handler which is triggered every time the value of that field changes. This event handler does not provide the value directly but instead provides an eventobject that can be used to get the value using event.target.value.</p><p>The setTodosetter function will be attached to the onChange event handler, which will pass the value of the input to the setter function through event.target.value. The value from the input is subsequently used by the setter method to update the state of todo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*BTDdgZeAfx2HQpl-b3qWNA.png" /><figcaption>Create a new Todo item</figcaption></figure><p>You can compare your project with <a href="https://github.com/m-yahya/react-todo-app/tree/91525c9b9a070baead9dd4828bcd79f00b8048ae">this</a> GitHub commit.</p><h4>2. Add Todo Item to Todos List</h4><p>After creating a new Todo, we need to add it to the Todos list. We’ll proceed in the same manner as we did when generating a new Todo item. We’ll create a new useState hook to keep track of the status of the Todos array and add new items to it.</p><pre>const [todos, setTodos] = useState([]);</pre><p>Next, let’s create an onClickfunctionaddTodoto add todo item to the Todos array. This function will be triggered when the Addbutton is clicked. It’s important to remember that the state should never be directly mutated. Therefore, we’ll need to make a copy of the Todos array before adding todo items to it. To copy the Todos array and add the todo item to it, we’ll use the Array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">spread</a> operator.</p><pre>const addTodo = () =&gt; {<br>    setTodos([...todos, todo]);<br>};</pre><p>We want to ensure that the value isn’t empty when adding a new Todo item to the list. This may be done with an if statement in our addTodofunction, which checks for an empty value. Also, after the value of the input is added to the Todos list, we want to clear the input field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*G8vnrbT2T2h0CKmp8hKfTw.png" /><figcaption>addTodo function to add a Todo item to the Todos list</figcaption></figure><p>Finally, we will pass this function to the onClickhandler of the Addbutton.</p><pre>&lt;button <em>className</em>=&quot;add-button&quot; <em>onClick</em>={addTodo}&gt;</pre><p><a href="https://github.com/m-yahya/react-todo-app/tree/c7629ea294c64420d6d6e531727e7965f7f5e7d4">This</a> GitHub commit reflects the complete code till this point.</p><h4>3. Display Todo Items</h4><p>We’ll make an ulwith the class todo-listto display the entries from the Todos list. We’ll iterate over the elements in the array with the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map()</a>method and then show them as liinside the ulelement. We will call the map() method with two arguments, the value of the current item being processed in the array and its index. For our purpose, the indexwill be utilized as the key of li.</p><p>We’ll make a new divwith the class todofor each item in the Todos list. This divwill have an liitem and a deletebutton for removing it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W36f6P7iAQxZOCSlv_myqw.png" /><figcaption>Display todo items</figcaption></figure><p>We want to make sure that the list isn’t empty just before we display it. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary operator</a> will be used to display the list items as well as a message if the list is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P31Kj1UwaxmmsD9LOKgP2A.png" /><figcaption>Conditionally display Todo items</figcaption></figure><p>You can compare your project with <a href="https://github.com/m-yahya/react-todo-app/tree/353f17c0f80cf93e6d714eb323df6c7042ddca07">this</a> GitHub commit to this point.</p><h3>Deleting Todo Items</h3><p>Let’s start by creating a onClickfunction that triggers when the delete button is clicked. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter()</a>method will be used in this delete function, which will construct a new array with all the entries that meet the stated criteria. In our example, we want to make a new Todos array that has all of the items except the one that is being deleted. Finally, update the state with newly created Todos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*bAS7J7adckzwDQ5bQwXG7A.png" /><figcaption>Delete todo item</figcaption></figure><p>Pass the deleteTodo method to the onClick handler of the delete button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*gzD4jpVmth_LFmjVHfNHcw.png" /><figcaption>Add deleteTodo function to onClick handler</figcaption></figure><p>You can find the code to this point <a href="https://github.com/m-yahya/react-todo-app/tree/93b2d2556559f60bcc6f1076f9134ab358e4a2e9">here</a>.</p><h3>Code Refactoring</h3><p>To gather the user input and show Todos items, we may rebuild our app by building two independent components, TodoInputand TodoList. In the srcdirectory, create two files: TodoInput.jsand TodoList.js. Fill each file with the content indicated in the code snippets below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XPfWHlWxorEN_pJb-7HIQ.png" /><figcaption>TodoInput component</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*yHEwV_eNlXLW9vAkMdUC2w.png" /><figcaption>TodoList component</figcaption></figure><p>Finally, import these two components in the App.js component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huw0vFqduUPFljBqMqJ8jw.png" /><figcaption>Import components in App.js</figcaption></figure><p>Now that you’re familiar with the basics, it’s time to get your hands dirty and start building your first React app. Good luck and Happy coding🎉🎉🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e935fe716179" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/react-todo-app-tutorial-e935fe716179">React Todo App Tutorial</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OLI dApps Portal]]></title>
            <link>https://medium.com/oli-systems/oli-dapps-portal-5bff38dc127b?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/5bff38dc127b</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[energy]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 11:59:16 GMT</pubDate>
            <atom:updated>2021-06-02T12:04:20.733Z</atom:updated>
            <content:encoded><![CDATA[<h4>BUILDING DECENTRALIZED APPLICATIONS</h4><h4>A collection of Ethereum based dApps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYEz6C5iVT9c7EIaCDyifA.png" /><figcaption><a href="https://energy-browser.my-oli.com/">OLI dAppa Portal</a></figcaption></figure><p>The interest in blockchain and distributed ledger technology (DLT) has accelerated significantly since the emergence of Bitcoin back in 2008.</p><p>Though blockchain is still a very young technology and undergoing continuous development, its use is gaining momentum in various industry sectors including finance, real estate, healthcare, identity management, and the energy sector. Technologies built on top of blockchain are known as Decentralized Applications (dApps). dApps are web applications that have a frontend and a backend just like common web applications. However, their backend is running on a decentralized peer-to-peer network. One of the most popular blockchain networks to develop dApps is Ethereum. It is a public blockchain and has developed its own programming language called Solidity to encode logic, rules, and instructions as smart contracts.</p><p>As many sectors are actively experimenting with blockchain, the energy sector is no exception. Blockchain along with other DLT and distributed energy sources (DERs) have opened new opportunities and challenges to revolutionize the way energy is traded, distributed, and the energy market is regulated. The potential of blockchain can be utilized across the energy value chain, building a peer-to-peer trading platform enabling producers to sell their energy directly to the consumers, generating green energy certificates, and integrating energy production and consumption in the energy supply system in a distributed way, etc.</p><p>At OLI Systems, we are building decentralized applications for energy markets based on the Ethereum blockchain network and smart contract technology.</p><h3>Overview of the Development Stack</h3><p>The dApps were developed using the following development stack:</p><ul><li><strong>Smart Contracts:</strong> developed using Solidity</li><li><strong>Frontend:</strong> written in JavaScript, HTML, CSS, Vue.js</li><li><strong>Backend:</strong> Volta Test network connected with Parity Ethereum client</li></ul><p>The architecture of the dApp is shown in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1g8whbpIVBdeIsB-zRDCZw.png" /></figure><h3>Dev Environments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*n99aora48Mi3NYoUiFV8pg.png" /><figcaption>Dev Environments</figcaption></figure><h3>Developer Tools and Libraries</h3><p>The dApps were built with the help of the following tools and libraries:</p><ul><li><a href="https://www.trufflesuite.com/"><strong>Truffle</strong></a><strong>:</strong> smart contract development suite for compiling, migrating, deploying, run tests, and interacting with a smart contract.</li><li><a href="https://web3js.readthedocs.io/en/v1.2.9/"><strong>Web3.js</strong></a><strong>:</strong> A collection of JavaScript libraries to set up a communication layer between the blockchain node and the frontend.</li><li><a href="https://www.parity.io/ethereum/"><strong>Parity Ethereum Client</strong></a><strong>:</strong> An Ethereum client to connect with the Ethereum blockchain node.</li><li><a href="https://vuejs.org/"><strong>Vue.js</strong></a><strong>:</strong> A progressive JavaScript frame to develop the frontend of modern web applications.</li><li><a href="https://solidity.readthedocs.io/en/v0.6.6/"><strong>Solidity</strong></a><strong>:</strong> An object-oriented programming language to write smart contracts.</li><li><a href="https://github.com/sc-forks/solidity-coverage"><strong>Solidity-Coverage</strong></a><strong>:</strong> Code coverage for Solidity smart contracts.</li><li><a href="https://plotly.com/javascript/"><strong>Plotly.js</strong></a><strong>:</strong> A declarative charting library built on the top d3.js.</li><li><a href="https://leafletjs.com/"><strong>Leaflet</strong></a><strong>:</strong> A JavaScript library to build interactive web maps.</li><li><a href="https://git-scm.com/"><strong>Git</strong></a><strong>:</strong> A distributed version control system.</li></ul><h3>The Development Workflow</h3><p>The development of the dApp can be divided into the following parts:</p><ul><li><strong>Backend Development:</strong> This part involves setting up a connection with the Volta node through the Parity client.</li><li><strong>Smart Contract Development: </strong>During this part, smart contracts are developed using Solidity programming language and then deployed over the blockchain.</li><li><strong>Development of the Web App:</strong> In this part, the front-end of the dApp is built with the Vue.js framework.</li><li><strong>Connecting Frontend with the Blockchain:</strong> The communication layer between the front-end and the blockchain backend is set up using the web3.js library.</li></ul><h4>1. Setting up the Volta node</h4><p>The setup starts with setting up the Ethereum blockchain development environment as a backend that is connected with the Parity client. For dApps backend, we are using the Volta network that is a test replica of the Energy Web Chain (EWC) and mostly used to test applications in a robust quality assurance (QA) environment. The network is connected by the Parity Ethereum client and uses a Proof of Authority (PoA) consensus mechanism.</p><h4>2. Smart Contract Development</h4><p>The project implements the business logic through smart contracts which are deployed on the blockchain. Smart contracts are a piece of program that represent the core logic of a dApp and are an integral part of the Ethereum blockchain. These contracts are developed using an object-oriented high-level programming language called Solidity. The development life-cycle of the smart contract, from developing to deployment on the blockchain, can be summarized in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NkLStHF7KCJldbDZlzcAA.png" /><figcaption>Smart Contract Lifecycle</figcaption></figure><h4>2.1 Truffle Framework</h4><p>We are using the <a href="https://www.trufflesuite.com/">Truffle framework</a> for the development of smart contracts. The Truffle provides a suite of tools to write smart contracts in Solidity, perform unit tests using Mocha and Chai, and deploy contracts on the Blockchain.</p><ul><li><strong>Truffle Unit Test</strong></li></ul><p>We will be using the truffle unit testing to test the core functionality of our smart contract. Under the hood, Truffle uses the Mocha testing framework and Chai assertion library to write the tests in JavaScript.</p><p>Following is the result of running truffle test on one of our smart contracts:</p><pre>Contract: ChargingOrigin<br>  ✓ should register a new asset (267764 gas)<br>  ✓ should fail to register an already registered asset (27720 gas)<br>  ✓ should send the charging info (33427 gas)<br>  ✓ should send the production value (281962 gas)<br>  ✓ should fail to send production value from the un-registered asset (24967 gas)<br>  ✓ should return the ETH address of given asset id<br>  ✓ should return the list of registered assets</pre><ul><li><strong>Gas Cost Estimation</strong></li></ul><p>The following table shows the gas and cost calculations for the execution unit tests and contract deployment. The market price data is fetched from <a href="https://coinmarketcap.com/">Coin Market Cap</a> and gas price is fetched from <a href="https://ethgasstation.info/">Eth Gas Station</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*4RomlzC5w3wzEZfYeflLaA.png" /><figcaption>Gas cost estimation</figcaption></figure><h4>3. Development of the Web App</h4><p>To interact with the smart contract on the Volta network, we built a UI component of the dApp in the form of a web app. The front-end of the project was built using modern web standards such as CSS, HTML, and the Vue.js framework. Additionally, two other JavaScript libraries, Plotly.js and Leaflet.js, were used to plot graphs and display geospatial distribution of resources, respectively.</p><h4>4. Connecting Frontend with the Blockchain</h4><p>The front-end of the dApp communicates with the Ethereum network using the JSON-RPC which is a stateless, lightweight remote procedure call (RPC) protocol using JSON for payload. This communication is done using a JavaScript library called Web3.js. It is a collection of libraries that allows our client-side application to communicate with the Ethereum network.</p><p>The interaction with the Ethereum network would be:</p><ul><li>Listening to the blockchain events like production and consumption data</li><li>Sending transactions (containing registration details, production, and consumption values) to the blockchain using smart contract methods</li></ul><p>To connect to the Ethereum node with JSON-RPC, we need to access the node using an Ethereum client, parity, or geth. In this project, we will connect with a locally running node connected with the Volta network using the Parity client.</p><h4>5. dApp UI Update Cycle</h4><p>As an overview:</p><ol><li>Currently, we are using a simulation setup written in Python to send the energy statistics over the blockchain using methods from smart contracts.</li><li>We are continuously polling the network to listen for the event emitted for successful transactions.</li><li>For each past and upcoming event, we perform some business logic and display them in the frontend.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5xq6f7-u-fIcShp-Qo3CA.png" /><figcaption>UI Update Cycle for Charging Origin dApp</figcaption></figure><h3>Energy Geo-Browser</h3><p>Among many use cases that can be built on blockchain technology, the Energy Geo-Browser app focuses on a transparent and efficient mechanism for presenting the dynamic and static attributes of energy assets, a decentralized mechanism for energy certificate issuance, and geo-visualization of spatially distributed energy sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGsgAdJv25ib0iBptCXefw.png" /><figcaption><a href="https://energy-browser.my-oli.com/browser">Energy Geo-Browser</a></figcaption></figure><p>The basic concept of the project is to present real-time information in a dynamic, secure, and transparent way. Thus, significantly reducing the complexities and additional costs associated with the internal operations because of third-party involvement. Though, we still have to pay the fee for the blockchain transactions. The prime focus of the project is to strengthen the energy market by modeling the energy transaction system that could lead to the energy certification layer on top of it.</p><p>The idea can be further extended to decentralized energy trading that will enable a direct relationship between producers and consumers.</p><h4>Key Features of Energy Geo Browser App</h4><ul><li>A registration mechanism for energy producers and consumers</li><li>Real-time energy production and consumption tracking</li><li>The decentralized energy transaction system</li><li>Geo visualization of energy resources</li></ul><p>The app shows one of the potential use cases of blockchain technology in the energy sector. The current dapp shows the very basic features of the geo-energy browser. Depending on the context of the implementation, the integration of DIDs or privacy-enabling components is possible. So, some regulatory and economical hitches are yet to be resolved.</p><h3>OLI Tokenization</h3><p>Renewable Energy Certificates (RECs) are important tools that represent the energy attributes as well as the information about how energy is generated. The certificate includes device type, locational information, owner details, and the total amount of energy generated. However, the energy is not incorporated in the RECs themselves. But, the renewable energy plants can issue 1 REC for every 1 MWh of the energy generated after they have fulfilled the criteria of REC generation.</p><p>The project has a certification page where a list of certificates is available that basically contains the Ethereum address of all the registered users. Once an address is clicked, a certificate has displayed that shows the energy and non-energy attributes of the producer such as device type, location, owner name, the total amount of energy produced, and geographical coordinates.</p><p>The process of certification is further extended to issue the digital token against the amount of energy produced at the rate of one coin per 1 MWh of energy produced. The token is a utility token and is designed on the ERC20 standard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwoJUWXq7yr0YFhjjadoAQ.png" /><figcaption><a href="https://energy-browser.my-oli.com/tokenization">OLI Tokenization App</a></figcaption></figure><h3>Asset Logging and Flex Control</h3><p>This application enables a DSO or TSO to transparently control assets in their respective grid area. Some examples of this are the curtailment of PV in case of a local over-supply or the control of a battery that is supplying a local energy community. This process is usually being done with uni-directional radio transmissions from the grid operator to the asset which is highly inaccurate and not suitable for state-of-the-art smart grids. Also, it is rather in-transparent. The asset owners have to trust the grid operators to make the right choices — and also to reimburse them correctly for any lost revenues in the case of PV curtailment.</p><p>With an increasing amount of assets, participants, and control processes in general, there is a demand for a platform that can integrate the following steps into one workflow:</p><ul><li>Onboard Assets, asset owners, and grid operators in a quick and simple way with low costs</li><li>Enable the grid operators to securely control assets</li><li>Log every control process to enforce transparency for the participants</li></ul><p>The backbone of this application is the “Volta” test network of the Energy Web Foundation. Every device owns its own key-pair which is being registered inside the smart contracts. These smart contracts also take care of the access restriction and the logging process. The participants don´t have to trust each other because the blockchain takes care of this, which reduces administrative overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3c_8UC2Fk2ZTOMKrZ5pDVQ.png" /><figcaption><a href="https://energy-browser.my-oli.com/logging">Asset Logging and Flex Control</a></figcaption></figure><h3>Charging Origin App</h3><p>The Charging Origin dApp is also built using smart contract technology on the top of the Ethereum network. The basic concept is to keep a record of events managing charging point power consumption and PV power generation data at a specific time interval.</p><p>The process starts with the one-time registration of the assets. After the registration, the assets will be able to send their data to the blockchain through smart contract methods. The front-end of the app will actively listen to the blockchain events in response to the transaction sent to the smart contract. Once an event is popped up, the event&#39;s return values will be processed to bind them to the respective asset and to calculate the energy share for each consumption event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4JqWq3Yff02EgoJDGtGfjg.png" /><figcaption><a href="https://energy-browser.my-oli.com/origin">Charging Origin App</a></figcaption></figure><p>In case you have any feedback, please drop me a line!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bff38dc127b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/oli-dapps-portal-5bff38dc127b">OLI dApps Portal</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamically Building Nested List from JSON data and Tree view with CSS3]]></title>
            <link>https://medium.com/oli-systems/dynamically-building-nested-list-from-json-data-and-tree-view-with-css3-2ee75b471744?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/2ee75b471744</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Sat, 01 May 2021 13:18:56 GMT</pubDate>
            <atom:updated>2021-05-01T13:14:37.157Z</atom:updated>
            <content:encoded><![CDATA[<h4>DYNAMIC TREE VIEW FOR NESTED LIST WITH CSS3</h4><p>A tutorial to dynamically build nested list from JSON data and vertical tree view with CSS3 only</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LXhDAF_JCmWUV8TEqJcilg.png" /></figure><p>Building a tree view for the hierarchical data is a common task in the front-end development of web applications. In most cases, hierarchical data is available in JavaScript Object Notation (JSON) which is a lightweight data format, and we need to represent this data as a tree on the webpage. In this tutorial, we will walk through the steps to dynamically create a nested list from the JSON data and style it to a vertically oriented tree view. The tutorial will use jQuery expression evaluation statement, Flexbox layout, and Pseudo-classes and Pseudo-elements from CSS3.</p><p>The goal of the tutorial can be divided into two parts:</p><ul><li>In the first part, we will learn how to dynamically build a nested unordered list of items from JSON data.</li><li>Then we will plot a vertically oriented tree view from the nested list with pure CSS3.</li></ul><p>The complete project code can be found <a href="https://github.com/olisystems/ul-tree">here</a>.</p><h3>1. Building Nested List from JSON data</h3><p>We will start with a simple data structure and then gradually move to the complex data structure. Let&#39;s consider the following simple data structure with a Parent and one Child:</p><pre>const data = {<br>  Parent: &#39;Child&#39;<br>}</pre><p>The HTML markup to create UI will look like the below snippet. For the sake of styling, we will use spanelements nested inside each li .</p><pre>&lt;ul&gt;<br>  &lt;li&gt;Parent<br>    &lt;ul&gt;<br>      &lt;li&gt; &lt;span&gt; Child &lt;/span&gt; &lt;/li&gt;<br>    &lt;/ul&gt;<br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Let’s write some JavaScript code to create HTML the markup for the above data. We assume that there could be three data types in the data:</p><ul><li>Object</li><li>String</li><li>Array</li></ul><p>In order to evaluate the above expressions, we will be using a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">switch</a> statement with <a href="https://jquery.com/">jQuery</a>. We will use $.type to evaluate three cases, a mockup of the function is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d57431b3a4584f14ea1ba8572f96d0/href">https://medium.com/media/b3d57431b3a4584f14ea1ba8572f96d0/href</a></iframe><p>We create an let markupArray = [&#39;&lt;ul&gt;&#39;] where we will push the HTML tags dynamically. The process will start by calling thecreateList function. As we are dealing with the JSON data, we fall into the first case that is the object . So in this case, we will write another function getItems to iterate over the items of the object. As we know that there in our data object, there is only one item Parent:&quot;Child” , so the function will return only one item Parent . The function will create a li parent item with nestedul for its children.</p><ol><li>create li for the Parent with an opening ul tag for the children.</li><li>call the createList function for the value of Parent ( Child in this case).</li><li>as Parent is a string , we will fall under the string expression of createList the function that will just push the li tags for Child to the markupArray .</li><li>at the end of the iteration, we will push the closing tags.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0609bfcfc7a943cbbef1a7c2c986168a/href">https://medium.com/media/0609bfcfc7a943cbbef1a7c2c986168a/href</a></iframe><p>Our modified createList function will become:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa848f4b7c090fc440657c5db5d9e3d6/href">https://medium.com/media/fa848f4b7c090fc440657c5db5d9e3d6/href</a></iframe><p>Next, we will create a main function to call the createList function and add a closing &lt;/ul&gt; tag to the markupArray . Inside the main function, we will make use of the regular <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join">Array.join</a> function which will convert an array to a string. Let’s create a div element &lt;div id=&quot;list&quot;&gt;&lt;/div&gt; and set the contents to the concatenated string using the jQuery <a href="https://api.jquery.com/html/">html</a> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb24c361a85137b06150bb99df014c51/href">https://medium.com/media/cb24c361a85137b06150bb99df014c51/href</a></iframe><p>Summarily, we passed the data to the createList expression evaluation function that will call the getItems function as the data is of type object . The getItems function will iterate over the items of data and create a li for parent item and a nested ul list for the children. We will then pass each child to the evaluation function to check the type of children. At this point, the child is a string so we just add a li to the children ul .</p><p>The source code up to this point can be found <a href="https://github.com/olisystems/ul-tree/tree/part-1">here</a>, clone the repository and open the index.html file in any of your favorite browsers.</p><p>Let’s consider the case where the parent element has more than one child, an array of children. In that case, we will update the array case from createList function as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74d947b082f500770af28ae0fa81888d/href">https://medium.com/media/74d947b082f500770af28ae0fa81888d/href</a></iframe><p>In the case of an array, we will iterate over the items of the array to further check their types. So the items will under one of the cases we have already defined i.e object, string, or array, and the function will execute the respective action according to the type. Let’s modify our data a bit and see this in action. If you have downloaded the project, then modify the data variable in main.js file and open the index.html file in the browser.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c2c1160d4611c9fa82843ad4537158a/href">https://medium.com/media/4c2c1160d4611c9fa82843ad4537158a/href</a></iframe><h3>1.1 Creating Family Tree</h3><p>At this point, we have successfully created the tree view from the nested JSON data. However, according to the original idea of the project, we want to plot a family tree structure where each member of the family has some bunch of details and a picture as well. The end result of this part will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*vEd031OwikTvuL7NvTIHlw.png" /><figcaption>1.1 Family Tree (without styling)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/145f6ea8d59570e2156697cebf233ade/href">https://medium.com/media/145f6ea8d59570e2156697cebf233ade/href</a></iframe><p>To adopt the structure as shown in the picture above, let’s clean up stuff and start from the beginning. Again, starting with the expression evaluation function createList, as our data is object, we will pass it to the getItems function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5453d9788f8b75acdafd7ea877c15c71/href">https://medium.com/media/5453d9788f8b75acdafd7ea877c15c71/href</a></iframe><p>If we look at our new data structure, we see that we have two objects: one data object and inside that there is aParent object. The process will go through in following steps:</p><ol><li>For the first, data object, we want to push it as a li item of root ul.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d7367d3444a976ae88a82e4bc5e5c0b/href">https://medium.com/media/2d7367d3444a976ae88a82e4bc5e5c0b/href</a></iframe><ol><li>For the Parent object, we will iterate over the details of Parent object. Let&#39;s create another getDetails function. Inside this function, we will loop over the object items, fetch the item value and push a span tag for each item.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc74fc4e2b929d3f30140b6ed3de614e/href">https://medium.com/media/dc74fc4e2b929d3f30140b6ed3de614e/href</a></iframe><p>We will fetch details of the Parent object and call the getDetails function inside the iteration of getItems function. It&#39;s important to note that here (details[detail]) we are trying to get the values of the items. In this way, first, we find the object in our data and iterate over the object to get its details. The modified getItems function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33dbbecacf7ccd26639e84823d07fe8a/href">https://medium.com/media/33dbbecacf7ccd26639e84823d07fe8a/href</a></iframe><p>The code up to this point can be found with <a href="https://github.com/olisystems/ul-tree/tree/e55b1336f6aea65b504124ca97fdbbc81a281af2">this</a> GitHub commit.</p><p>Before moving on, let’s tweak one change for the image. Right now, we just the image name but we want to place an iamge there. For this, we will place a if - else statement to check if the detail is an img and put the img tag instead of span element. Also, in the data object, we can move imge item to the top of other items, and set style for span and img element as display:block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8319268d2200ab0c5871becf23da2ebf/href">https://medium.com/media/8319268d2200ab0c5871becf23da2ebf/href</a></iframe><p>You can compare the GitHub <a href="https://github.com/olisystems/ul-tree/tree/74a033021bc32290c9f8c66693dbca46bb112ef2">commit</a> for the code up till now.</p><p>Next, we have to deal with the children and for this let&#39;s add an array of children to the Parent element. It&#39;s important that the child should adopt the same structure as the parent i.e. some details and an array of children.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37dd3b2e540879d4a3b212f3ccbd1dce/href">https://medium.com/media/37dd3b2e540879d4a3b212f3ccbd1dce/href</a></iframe><p>Now we have three cases to evaluate: if the key of the item inside the object is img, children or something else. We already have approaches to deal with the img and other stuff, so now we will proceed with the children array. In essential, we need to create an ul that will contain all the items in the array as li. In this particular case:</p><ol><li>first, we will push a &lt;ul&gt; tag as this will be a nested list inside the parent li.</li><li>Then, loop through the items of the array and pass each item to the getItems function. This function will push a&lt;li&gt; tag and then call getDetails function (as items inside the array are objects) for each item. Thus, repeating the same process we did for the parent element.</li><li>At the end of the loop, we push the closing tag &lt;/ul&gt; to the markupArray.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1329853ba0fe77e9d9390c75a38cb8/href">https://medium.com/media/3f1329853ba0fe77e9d9390c75a38cb8/href</a></iframe><p>With this, we are done with the first part of the tutorial. You can find the complete code to this point <a href="https://github.com/olisystems/ul-tree/tree/part-3">here</a>.</p><h3>2. Plotting Vertical Tree View</h3><p>The process of plotting vertical tree view can be broadly divided into the following steps: Flip the horizontal view to vertical view Draw connectors between the elements</p><h4>2.1 Flip List to Vertical View</h4><p>This is a fairly easy part and can be easily achieved using CSS <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">Flexbox</a> layout. In this case, we will set:</p><ul><li>ul elements to the vertical direction</li><li>li elements to the horizontal direction</li></ul><p>The images are quite big, so the image width and height are set to 50px.</p><p>From the data structure, we know that ul is the parent element and li is the child element. To use the flexbox layout, we need to make the parent element a flex container. The elements inside the flex container will become the flex items. By default, the li are block elements and are vertically stacked. Flexbox layout will align the flex items in a row in case direction is not specified. It is important to note that flexbox only applies to the items of the flex container, not to the nested items of flex items. However, for the current case, the nested items are again ul so flexbox layout will be applied to them as well. As a result, we will have rows for all the ul and nested ul as well. Additionally, we will remove the default indentation and list-style as well.</p><p>As a result, we will see a vertical view of ul with the li in the horizontal direction (image 2 in the following screenshot). To change the direction of li, we will apply the flexbox model to it and set the flexbox direction as column (image 3). With these two simple styles, we have flipped the view to the horizontal tree view. <a href="https://github.com/olisystems/ul-tree/tree/a77a59fd70870598d1023b888a863ed32df40f39">This</a> Github commit reflects the code till this point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D6jcBboGKQPnFYM3DXOGbA.png" /><figcaption>Tree view without connectors</figcaption></figure><h4>2.2 Draw Connectors</h4><p>In this section, we will draw connectors:</p><ul><li>between the parent and siblings</li><li>between the siblings and [sub]siblings</li></ul><p>To achieve this, we will make use of <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements">Pseudo-classes and pseudo-elements</a>. To place the connectors horizontally in the middle and vertically on the top of the element, we will use left:50% and top:0 position specifiers respectively.</p><ul><li>Let’s start with adding vertical connectors before each parent element(ul), except the very first parent element. This will be done using the ::before pseudo-class relative to the ul, along with adding a padding-top to the ul equal to the height of the pseudo-element. To hide the connector before the very first element of ul, we will use pseudo-class :first-child to set the display of pseudo-element ::before to none. The result of this can be seen in image 1 of the below screenshot.</li><li>Adding connectors between the siblings will be done in two steps. First, we will add vertical connectors before each li element using ::before pseudo-element relative to the parent li. In the next step, we will place horizontal connectors for the siblings using the ::after pseudo-element with width and border-top properties. The resultant image is shown as image 2 in the screenshot below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X2TEsheYDpk_7F3FfMFVw.png" /><figcaption>Tree view with connectors</figcaption></figure><p>It can be seen from the above screenshot that we need to fix some issues:</p><ul><li>First, remove the horizontal connector from the very first element. This issue can be fixed with the use of only-child pseudo-class to hide the display of pseudo-elements in case there is only one child.</li><li>Next, remove the left and right connectors for the first and last element of a group respectively. This will be fixed using first-of-type and last-of-type pseudo-classes with a width of 50% and position right and left 0 respectively.</li><li>Finally, remove the ::before connects for the single element in the group using padding-top:0 and display:none. <br><a href="https://github.com/olisystems/ul-tree/tree/7967624000ec6a6468e70675df5ebbf74e1b6b78">This</a> GitHub commit shows the code up to this point.</li></ul><h4>2.4 Formatting Elements</h4><p>To add some styles, we will wrap details span elements into a single div element. The following git diff screenshot shows what has been changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DJf8yleXNnvUVniS.png" /><figcaption>Git diff screenshot</figcaption></figure><p>We will add some padding between the children, background color, and text transformation. The updated CSS code can be found <a href="https://github.com/olisystems/ul-tree/blob/f00713db73a6947df1ef0bc246f656ac28ff8f6c/css/main.css">here</a>.</p><p>Happy coding🎉🎉🎉.</p><h4>Resources:</h4><p>Images used in this tutorial are downloaded from <a href="https://www.flaticon.com/downloads-limit">Flaticon.com</a></p><h4>References:</h4><ul><li><a href="https://www.freecodecamp.org/news/understanding-flexbox-everything-you-need-to-know-b4013d4dc9af/">Understanding Flexbox</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements">Pseudo Classes and_Pseudo Elements</a></li><li><a href="http://fractaledmind.com/articles/css-tree-vertical/">Fractaledmind - CSS Tree Vertical</a></li><li><a href="http://thecodeplayer.com/walkthrough/css3-family-tree">Thecodeplayer - CSS3 Family Tree</a></li><li><a href="https://github.com/dabeng/OrgChart">Dabeng - OrgChart</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee75b471744" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/dynamically-building-nested-list-from-json-data-and-tree-view-with-css3-2ee75b471744">Dynamically Building Nested List from JSON data and Tree view with CSS3</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Energy Singularity: A future closer than we would have imagined]]></title>
            <link>https://medium.com/oli-systems/energy-singularity-a-future-closer-than-we-would-have-imagined-5263de73a9ba?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/5263de73a9ba</guid>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[peer-to-peer]]></category>
            <category><![CDATA[smart-grid]]></category>
            <category><![CDATA[energy-market]]></category>
            <dc:creator><![CDATA[Mukund Wadhwa]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 10:13:31 GMT</pubDate>
            <atom:updated>2021-01-14T10:13:19.367Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last few years, peer to peer energy trading has been slowly gathering more and more attention. Initially, it was only the research community which was fascinated by the potential of having end customers trading energy among themselves, but the commercial viability of such a service is slowly being realised as well. <a href="https://lo3energy.com/">LO3Energy</a> launched one of the first Proof of Concept (PoC) for Blockchain based Local Energy Markets (LEMs) in the form of <a href="https://www.brooklyn.energy/">Brooklyn Microgrid</a> back in 2016 and sparked the interest from different fields. Since then a lot of PoCs and start-ups have popped up around the world wanting to showcase the cellular grid structure (where community self-sufficiency is prioritized) compared to standard uni-directional (from large power plants to end customers) system. One of the start-ups launched during the same time is <a href="https://gridsingularity.com/">GridSingularity</a>. Since their establishment, this Berlin-based start-up has been working on creating an open-source platform that can provide the end customer high degrees of freedom in their energy-related interactions as well as the grid operator a clear view of the energy flows in their controlled network. After testing their approach using simulated household consumption and generation data and testing the limits of their software in the <a href="https://gridsingularity.medium.com/en-route-to-energy-singularity-odyssey-momentum-learnings-from-the-2020-chaos-experiment-8dc38ff26869">Chaos Theory Experiment</a>, they launched their first Canary Network during <a href="https://www.odyssey.org/">Odyssey Momentum</a>, one of Europe’s leading hackathon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5t8Dk1Am7uFQoVweyKRTjA.jpeg" /></figure><p>The story behind the ‘Canary Network’ goes back to the early mining days where canaries served as air toxicity measurement tool and thus reduced the chances of unexpected complications for the miners. If you are thinking of the famous phrase ‘canary in the gold mine’, you might be on the right track. The Canary Network is the testing process of connecting electricity meters (both digital and smart meters) from household and businesses to GridSingularity’s market platform i.e D3A and letting the autonomous intelligent agents trade electricity on the behalf of their owners. In a way, <a href="https://en.wikipedia.org/wiki/Digital_twin#:~:text=A%20digital%20twin%20is%20a,be%20used%20for%20various%20purposes.">digital twins</a> of the real energy assets were created. Connecting the end customers to D3A was carried out by <a href="https://www.my-oli.com/de/">OLI Systems</a> using Smart Meter Gateway (SMGW) Interface and OLI boxes (embedded hardware from OLI Systems with multi layer functionality) using the knowledge gained in projects such as <a href="https://auew.de/blog/2019/08/projekt-pebbles/22/">Allgäu Microgrid</a>, <a href="https://pudi.lubw.de/detailseite/-/publication/10033?_de_xdot_lubw_pudi_frontend_web_portlet_DetailPortlet_backURL=https%3A%2F%2Fpudi.lubw.de%2Fprojekte%3Fp_p_id%3Dpsp%26p_p_lifecycle%3D0%26p_p_state%3Dnormal%26p_p_mode%3Dview%26_psp_mvcPath%3D%252Fhtml%252Fprojectsearch%252Fview.jsp%26_psp_keywords%3D%26_psp_extendedSearch%3Dfalse%26_psp_facetFilterQuery%3D%2540pudipr%253Aassoc_pudipr_projecttype_pudiprt_label%253A%2526%252334%253BUmweltforschung%2526%252334%253B%26_psp_cur%3D4%26_psp_delta%3D10%26_psp_orderByCol%3Dproject-end-new-old%26_psp_orderByType%3Dasc">DOSE</a> and <a href="https://www.csells.net/en/">C/Sells</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7MinvM71sG8iPTUC62XCg.png" /><figcaption>OLI Box connected to digital meter (left), <a href="https://medium.com/u/b5042bccf5e8">Felix Foerster</a> explaining how data is collected using Smart Meters (right)</figcaption></figure><p>During the hackathon, the ‘<a href="https://www.odyssey.org/hackathon-2020-grid-singularity-challenge-interact-with-digital-twin-simulations-of-multiple-transactive-grids/">EnergySingularity</a>’ challenge was divided into two streams. Stream 1 required the participants to create and operate the autonomous intelligent agents that traded on behalf of the end customers in the simulated energy communities. In Stream 2, the participants had to tackle the social aspects of the problem i.e. how to incentivize the end customers to get involved in a system which on one hand can seem complicated and adds to the things they need to care about, and on the other hand, provides them with an opportunity to fulfill the needs they are yet to realize. The results of Stream 2 have been discussed by GridSingularity in <a href="https://gridsingularity.medium.com/energy-singularity-challenge-2020-social-energy-networks-157b390e5f39">Energy Singularity Challenge 2020: Social Energy Networks</a>.<br>Our team i.e. OLI Team (The combination of OLI Systems+<a href="https://new.siemens.com/global/en/company/about/businesses/smart-infrastructure.html">Siemens Smart Infrastructure</a> and <a href="https://insignal.ai/">InSignal</a>) took part in Stream 1 where we developed and deployed our autonomous intelligent agent strategy that optimized itself based on the needs and requirements of every individual household that was part of the community.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARuD9klRHKzc3UqrWkS0Fg.png" /><figcaption>OLI team station in the odyssey universe</figcaption></figure><p>Over the weekend of the Odyssey Momentum, there was a lot of interesting discussion based on the results obtained from different grid fee experiments. The discussions about the future energy systems along with the results of the hackathon challenges have been covered in detail by GridSingularity in <a href="https://gridsingularity.medium.com/energy-singularity-challenge-2020-testing-novel-grid-fee-models-and-intelligent-peer-to-peer-6a0d715a9063">Energy Singularity Challenge 2020: Testing Novel Grid Fee Models and Intelligent Peer-to-Peer Trading Strategies</a>. But I would still like to talk about some of the key takeaways and questions that remain open for me.</p><p><strong>The end customers need to be in the driving seat</strong></p><p>It is a common conclusion drawn in the field of Smart Grids that the end customer of energy can not be sitting on the sidelines if we want to do a transition to cleaner and sustainable sources of energy. But the question always comes down to what kind of system design can be implemented to create welfare for all actors involved. Since the motivation of participation of every end customer can be a combination of intrinsic (being part of a community, helping in reducing carbon emission, etc.) and extrinsic (reduction in electricity bills, showcasing your good deeds, etc.) values, the regulations and market need to facilitate fulfillment of their individual motivations. In short, for LEM solution that is to be adopted by the masses, end customer should be able to see the fulfillment of their motivations by including their energy assets (solar panels, batteries, heat pumps, etc) in the local market. In the discussions, it was also realized how there was a huge need for transparency in asset decision making from the customer end.</p><p>Trust is an important key for the mass adoption of a solution. People need to feel comfortable with the knowledge or information they get out of the interface they use and also have the security taking over control if that is something they desire. The autonomous agent needs to be created as a complete representation of their believes and values while keeping it simple as well. In order to also comply with the data protection regulations (<a href="https://en.wikipedia.org/wiki/General_Data_Protection_Regulation">GDPR</a> in case of EU countries), it would be mandatory to obtain clear consent from the end customers before an autonomous agent makes a decision on their behalf.</p><p>The questions that still remain unanswered are:</p><ul><li>Should the end customer be obliged to provide access to their energy asset (for say grid balancing) if the incentives provided do not match their expectations?</li><li>How much information is enough for the end customer to feel comfortable with their energy asset interaction to the LEM? And what might be considered as an overkill of information?</li></ul><p><strong>Role of grid fees</strong></p><p>In the <a href="https://www.next-kraftwerke.com/knowledge/liberalization-energy-markets">status quo</a>, <a href="https://www.investopedia.com/terms/w/wholesale-energy.asp">wholesale energy trading</a> (actual trading of energy in kWhs) is completely separated from congestion the power flow would be causing in the grid. The balancing of the congestion comes down to the grid operators and the cost is ultimately divided and passed to the end customers in form of grid fees. But when you imagine buying electricity from your neighbour, the application of the grid fee in the current form does not make sense as only a fraction of the public grid is used for the trade. Using IoT and blockchain-based solutions, generation and consumption can be tracked in real-time. This enables the possibility of a hierarchical grid fee system (<a href="https://gridsingularity.github.io/d3a/constant-fees/">as considered in D3A market approach</a>) to be developed where the assigned grid fee corresponds to the grid usage and congestion created for the trade to take place. Information about the grid fee applied at every hierarchical level can help the end customers better understand the cost of trading electricity in an LEM and provide the trading preferences for the autonomous agent.</p><p>Additionally, the grid operators can be active participants in an LEM structure. By actively changing the grid fee at a level, the cost of congestion can be included and hence energy trading at that level can be influenced. This is one of the many market incentives that can be used to activate flexible assets such as batteries, electric vehicles (EVs), heat pumps, etc for <a href="https://en.wikipedia.org/wiki/Energy_demand_management">demand-side management (DSM)</a>.</p><p>Some of the questions that still need to be investigated are:</p><ul><li>Should the grid fee be calculated and reported to the end customer before the trading starts or post-delivery?</li><li>If beforehand, how long before should the grid fee schedule be communicated?</li><li>Should there be a separate market for trading flexibility for last-minute grid balancing via DSM?</li></ul><p><strong>Regulations for LEMs</strong></p><p>For a fully functioning LEM, a lot of different actors need to be involved to fulfill very specific roles. Some roles can be combined, while some need to be completely separated. Therefore, the requirements and objectives of every actor need to be understood and their responsibility clearly defined with regulations. The actors and the roles defined under the current research of LEMs are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QECmeGiEcRkbEbKUEXxc4w.jpeg" /><figcaption><a href="https://www.researchgate.net/publication/344567698_Analysis_of_local_electricity_markets_in_Germany_using_simulation">Actors and their roles in LEM</a></figcaption></figure><p>Since a significant share of the target audience of the LEMs are households, customer protection needs to be at the forefront of the regulation. There have been issues such as <a href="https://fsr.eui.eu/market-abuse-abuse-market-power-wholesale-energy-markets/">abuse of market power</a> in the wholesale energy markets, that need to be avoided in order to maintain the trust of end customers in the system. Therefore, detailed studies need to be done to understand the scope of such issues and create regulations for mitigation and to provide a guideline in case of conflicts. The regulation would also decide the margins available for trading in the local market and the business model of all the actors involved would also be dependent on it. Additionally, the current grid fee structure would disproportionally burden the non-LEM end customers to support the larger grid in case of mass adoption of LEMs. Therefore, the grid fee structure would also need to be evolved. Some changes in the regulations have already been seen in countries like <a href="https://www.idealista.com/en/news/lifestyle-in-spain/2020/08/04/7761-the-royal-decree-on-self-consumption-of-electricity-relaunches-solar-energy-in">Spain</a> and <a href="https://www.pv-magazine.com/2020/03/03/energy-community-provisions-for-italy/">Italy</a> over the last months based on the Energy Community aspects mentioned in EU level directives and <a href="https://ec.europa.eu/energy/topics/energy-strategy/clean-energy-all-europeans_en">Clean Energy for All Europeans Package (2019)</a>. But in countries like Germany, the directives are yet to be transposed in national law and therefore there aren’t many good options available for small renewable assets that stop receiving the fixed feed-in tariff under the <a href="https://en.wikipedia.org/wiki/German_Renewable_Energy_Sources_Act">Renewable Energy Source Act</a> from 2021.</p><p><strong>Risk of trading</strong></p><p>The introduction of LEMs have the potential to reduce the electricity bills of the end customers but also can cause them to increase based on the trading strategy used and the liquidity in the LEM. The variation in prices of electricity was also observed during the hackathon in a different grid fee experiment (as also shown in the community trading price graph below). So far it has been assumed that the end customer participating in the market understands these risks and is onboard. But for many end customers which are not satisfied with these financial risks but are excited about the community aspects, this might be a deal-breaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yi4VcOqe8LSvFcbcsSa5Kg.png" /><figcaption>Community trading prices for Hackathon Grid fee experiment 3 in a simulation operated by Oli Team</figcaption></figure><p>Therefore, for mass adoption of LEMs the end customer should have the option to avoid financial risks and still be an active trader in the local market. The service package provided by an aggregator (as defined in actors and their role above) should include the possibility to switch the preferences based on the financial risk the end customer is willing to take and focus more on trading locally generated green electricity.</p><p><strong>Need for new performance indicators</strong></p><p>As discussed earlier end customers participating in the LEM have very specific motivations. Similarly, other actors involved for functioning of an LEM can have motivations that are a combination of various factors such as reducing the cost of investment in grid infrastructure, promotion of clean sources of electricity, creating solidarity within local communities, implementation of new technology, offering exciting new products, etc. Quantifiable performance indicators are required for reflecting these complex motivations in order for an LEM to be working in benefit for all the actors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIwKgWXRgoJHbxw461HatQ.png" /></figure><p>After multiple rounds of lengthy discussions, our team came up with one such performance indicator for the end customer during the lunch break at a <a href="https://burreatos.com/">Mexican fast food place</a> (would highly recommend to try out if you are in Stuttgart), the ‘Burrito Factor’. Burrito Factor (BF) considers the financial state of a end customer and reflects the performance of the strategy compared to the average performance of the community in a given time period. In case of a machine learning based algorithm such as Q-learning, increase in BF value can indicate drop in performance and hence a re-learning process can be triggered.</p><p>As part of the OLI team, we designed an autonomous agent for the hackathon with the idea of an end customer who understands their needs and desires well and has communicated them to the agent. Throughout the hackathon, we realized where our model was lacking and what other aspects we should be considered as well. We were able to implement some of the changes in the final optimization round and saw it bearing fruits already. Another thing worth mentioning is the openness among the teams to share their knowledge and experience while working on their agents. This is something I personally have not seen before among teams which are competing with each other.</p><p>My time in the hackathon has made me quite excited about the possibilities and the challenges we have in store for us to bring LEMs to the masses. Additionally at OLI Systems, we are working on projects such as <a href="https://www.dena.de/newsroom/meldungen/dena-testet-blockchain-basierte-infrastruktur-fuer-die-identifizierung-von-anlagen-im-energiesystem/">BMIL</a> and <a href="https://www.aws-institut.de/research/netzstabilisierung-mittels-blockchain/">Flexchain</a> and BEST with partners from utilities, grid operators, hardware manufacturers as well as research institutes to develop decentralized smart grid solutions for Germany. These solutions would hopefully help in answering some of the open questions I raised regarding the LEMs. The design of GridSingilarity ecosystem is transparent and comprehensible which should help in easy on-boarding of all the actors. With larger utilities such as E.ON and Engie being the challenge partners for the hackathon, it seems somewhat inevitable that LEM will move out of the PoC phase to the commercial product phase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5263de73a9ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/energy-singularity-a-future-closer-than-we-would-have-imagined-5263de73a9ba">Energy Singularity: A future closer than we would have imagined</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Smart Meter Gateway Part I: The Basics]]></title>
            <link>https://medium.com/oli-systems/the-smart-meter-gateway-part-i-the-basics-474170e5b607?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/474170e5b607</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[energy-management-system]]></category>
            <category><![CDATA[energy-efficiency]]></category>
            <category><![CDATA[smart-meter]]></category>
            <category><![CDATA[digital-transformation]]></category>
            <dc:creator><![CDATA[Felix Foerster]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 13:49:53 GMT</pubDate>
            <atom:updated>2020-10-12T13:49:52.944Z</atom:updated>
            <content:encoded><![CDATA[<p>There is hardly any topic in the energy sector being discussed more than metering — and for good reason! Meters are the building blocks for almost any energy system. Without meters, there is no billing and no accounting — but even worse would be the lack of identity and trust. If we can´t track production and consumption values tied to specific entities for specific intervals, how is anyone — from small to large scale — supposed to use their energy assets efficiently?</p><p>In the context of a more volatile, dynamic, and complex energy system, meters will have take over an even more important role. Because renewables produce electricity intermittently, we have to put further care in orchestrating production and consumption — and also securely bill it accordingly.</p><p>Besides reducing the current standard interval for energy billing and accounting (yearly) to smaller timeframes (e.g. quarter-hourly) to further incentivize the actual matching of production and consumption, we also might want to add additional functionalities to the meter. Why? Because the <strong>Smart Meter </strong>is already interconnected to remote systems (or in other words: it has Internet or VPN access) and could also do multiple other things like getting specific sets of data from energy assets or device-control. Using a one-device-fits-all paradigm makes a lot of sense to avoid uncontrolled growth of non-interoperable solutions and to decrease investment, operation, and maintenance costs. And that´s exactly the way the German government was thinking — and started the development process of the SMGW (Smart Meter Gateway) framework.</p><p>In this article, a compact introduction to the SMGW framework is given.</p><h4><strong>Power Metering - A history that spans more than a century</strong></h4><p>Meters have undergone many changes over the years. Knowing the technical history of metering from past to present is helpful to understand the current scenario better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*HcCVaK4depLIoWAXII4_EQ.png" /><figcaption>Figure I: Ferraris Meter (left) and a modern metering unit (right) with a SMGW (Source: Verbraucherportal-BW)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*mj8-YwYvCGr9a_LeJqoKWA.png" /><figcaption>Figure II: Modern modern metering units and an OLI BOX (Source: OLI Systems GmbH)</figcaption></figure><p>The analogue, electro-mechanical “Ferraris” meter with its rotating metal disc is probably the one most of us know. It is very sturdy, simple, accurate and can operate for decades. Depending on the country, they are being read out either by the resident of the building or grid-operator personnel on a monthly or yearly interval. The meter reading is then manually sent to the grid operator with a handwritten form, a letter or a digitally via a webpage.<br>The next generation consisted of a wildgrowth of digital meters. The power measurement changed from the electro-mechanical approach to purely electrical. Because there are no more turning components in the meter, a digital display is also needed to show the current readings. Depending on the individual regulation of the country, the meter might also have multiple local interfaces - optical, electrical, wireless, unidirectional and bidirectional - all sort of combinations are possible. Even though they are the product of a digitalization process they very often lack a critical component: the communication unit. While the data is all there - in the meter - there is often no way to securely transmit it to the grid and market operator, to retailers and other third parties. <br>Lastly, what we would like to call the third generation of meters, are the so-called ‘<strong>moderne Messeinrichtung</strong>’ (mMe or ‘<strong>modern metering unit</strong>’). These are standardized digital meters according to the demands of the German regulators and industry. They feature a fixed set of interfaces - for both local devices and humans to interact with. But similar to existing digital meters they also lack the communication component to transmit data from the meter to remote and external systems.</p><p>The mMe is designed in a way it can easily be combined with that missing communication component and form an intelligent metering system (iMSys). In Germany, the <strong>Smart Meter Gateway</strong> (SMGW) is that missing unit.</p><p><strong>Law</strong></p><p>In Germany, the “Gesetz zur Digitalisierung der Energiewende” (engl: law for the digitalization of the energy transition) was passed in 2016 to build-up the legal framework for the deployment of <strong>iMSys</strong> in Germany. Starting from 2020, consumers with more than 6,000 kWh annual consumption and prosumers with more than 7 kWp installed PV capacity will be required to have an iMSys installed. As a DENA study states, almost 16 million intelligent measurement systems are expected to be in use by 2032.</p><h4><strong>Balancing Transparency, Security, Privacy and Efficiency</strong></h4><p>When digitalizing any system, a number of design objectives are always apparent, that sometimes contradict each other:</p><ul><li>Transparency and Integrity: An maximum of information should be disclosed at all times for all possible stakeholders about static and dynamic information of the system in use. For example, if things get intransparent and the ‘end-customer’ becomes increasingly skeptical about who uses their data or what exactly it contains, the acceptance might diminish. But also grid-operators or retailers that want to use the data for various applications need a maximum of transparency about its origin and integrity. Of course, keeping everything transparent has its downsides.</li><li>(Data) Security: The data measured by an iMSys should only be visible to a few participants in the system and should not be disclosed into a public domain. Therefore, security zones and a straightforward permissioning scheme have to be implemented and kept secure at all costs. Not only should we keep malicious actors away from the data as it enters the heights of B2B communication, but also every single iMSys is installed in an hostile environment. Basements, transformer stations and other locations like this are ideal places for trying to hack into a Smart Meter Gateway. Therefore also device-level security has to be implemented.</li><li>Efficiency: Installing IoT devices, maintaining communication lines and keeping everything up-to-date is an expensive task in any possible context. While there should be no compromise on security, a poorly designed system can easily cost way more than necessary - and still bring no distinct advantage over an analogue implementation</li></ul><p>To ensure the design objectives are met the BSI (German Federal Office for Information Security) and PTB (German National Metrology Institute) started working on a precise list of requirements and a system architecture which resulted in the technical documents (BSI TR-03109). The technical guideline has six main subdocuments which are focusing on “Gateway architecture”, “Safety module”, “Cryptographic specifications”, “Public-Key infrastructure” and “SMGW administration”.</p><p>The central design component of the SMGW ended up to be a <strong>three area/zone network</strong>.</p><h4><strong>Local areas and different parties of the framework</strong></h4><p>The SMGW itself has divided into three main security areas or zones:</p><ol><li><strong>Home Area Network</strong> - The HAN is its own network supposed to interconnect the energy devices (Inverters, batteries, electric-vehicles) with the smart meter gateway. It is highly restrictive and only permissions specific, pre-validated and pre-registered devices to route their communication through the other zones.</li><li><strong>Wide Area Network</strong>: The WAN is supposed to connect the SMGW and the other zones to the administrator (SMGWA) and external market participants (EMP) that for example could represent the grid operator, a retailer or an aggregator. This network is highly restrictive, has specific rules and usually forms a VPN.</li><li><strong>Local Metrological Network</strong>: The LMN connects the local <strong>modern metering units </strong>to the SMGW for a secure readout with high integrity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*c1zXtdk1Lr2PDAL_2MzLAA.png" /><figcaption>Figure II: SMGW and its environment (Source: BSI)</figcaption></figure><p>Made out of three different zones, the SMGWs ‘central’ task is to route communication from one zone to another. Those zones represent basically a Smart Grid: The end-customer is connected to the HAN with the help of an certified installer to the HAN. The other participants (grid operator, retailer, aggregators) are connected to the SMGW via the WAN, while the local certified and secure meters all communicate through the LMN.</p><p>For the WAN, further levels of permissioning apply. The Smart Meter Gateway Administrator (SMGWA) for example has special rights in comparison to the External Market Participants (EMPs). Besides being able to update the SMGW with a new firmware, they can also configure it with new profiles in order to support an ever-changing set of EMPs. The EMP however, only can access the SMGW via the Administrators permission - and even then the SMGW itself will start the connection process (“bottom-up”).</p><p>The whole setup enables in first instance the quarterhourly readout of a meter installed at a SMGW. Besides that, external device-control by an EMT via the WAN is also possible, for example in the context of PV-curtailment.</p><p><strong>That should be it for Part I! <br>Next time we will take a look at the WAN to HAN communication in greater detail, while Part III will report about how distributed ledger technologies (DLTs) can augment the SMGW architecture</strong>.</p><h4><strong>References</strong></h4><p>Bundesamt für Sicherheit in der Informationstechnik. Technische Richtlinie BSI TR-03109–1: Anforderungen an die Interoperabilität der Kommunikationseinheit eines intelligenten Messsystems; Bundesamt für Sicherheit in der Informationstechnik: Bonn, Germany, 2013. Source : <a href="https://www.bsi.bund.de/DE/Publikationen/TechnischeRichtlinien/tr03109/index_htm.html">https://www.bsi.bund.de/DE/Publikationen/TechnischeRichtlinien/tr03109/index_htm.html</a></p><p>Physikalisch-Technische Bundesanstalt (PTB) Anforderungen 50.8A Dezember 2014 <a href="https://oar.ptb.de/files/download/56d6a9e2ab9f3f76468b4618">https://oar.ptb.de/files/download/56d6a9e2ab9f3f76468b4618</a></p><p>Kroener, N., Förderer, K., Lösch, M., &amp; Schmeck, H. (2020). State-of-the-art integration of decentralized energy management systems into the German smart meter gateway infrastructure. Karlsruhe. <a href="https://doi.org/10.5445/IR/1000120981">https://doi.org/10.5445/IR/1000120981</a></p><p>“Smart meter — Deutsche Energie-Agentur (dena).” [Online]. Available: <a href="https://www.dena.de/en/topics-projects/energy-systems/digitalisation/smart-meter/">https://www.dena.de/en/topics-projects/energy-systems/digitalisation/smart-meter/</a>. [Accessed: 19-Sep-2020].</p><p>Messstellenbetriebsgesetz: <a href="https://www.gesetze-im-internet.de/messbg/BJNR203410016.html">https://www.gesetze-im-internet.de/messbg/BJNR203410016.html</a></p><p>Figure I:<br><a href="https://www.verbraucherportal-bw.de/,Lde/Startseite/Verbraucherschutz/Smart+Meter">https://www.verbraucherportal-bw.de/,Lde/Startseite/Verbraucherschutz/Smart+Meter</a><br>Figure III: <a href="https://www.bsi.bund.de/DE/Themen/DigitaleGesellschaft/SmartMeter/SmartMeterGateway/smartmetergateway_node.html">https://www.bsi.bund.de/DE/Themen/DigitaleGesellschaft/SmartMeter/SmartMeterGateway/smartmetergateway_node.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=474170e5b607" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/the-smart-meter-gateway-part-i-the-basics-474170e5b607">The Smart Meter Gateway Part I: The Basics</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why should you care about the digitalization of your electricity?]]></title>
            <link>https://medium.com/oli-systems/why-should-you-care-about-the-digitalization-of-your-electricity-68c475a8d4e4?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/68c475a8d4e4</guid>
            <category><![CDATA[electricity-market]]></category>
            <category><![CDATA[smart-grid]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[energy-management-system]]></category>
            <category><![CDATA[energy-transition]]></category>
            <dc:creator><![CDATA[Mukund Wadhwa]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 07:53:09 GMT</pubDate>
            <atom:updated>2020-09-07T07:46:56.534Z</atom:updated>
            <content:encoded><![CDATA[<p>The Corona pandemic highlighted the lack of foresight we have about the future. Scientists had been warning us for years about the possibility of a global pandemic. But no one was really prepared for anything like we are going through right now. Digitalization of so many sectors has been accelerated across the globe to cope with some of the challenges. Things that were not imaginable a year ago are the new normal today. The downfall of cash payments in Germany in recent months is one of the big examples of this change. In the pre-pandemic era, the phrase ‘cash is king’ was applicable in the country as about <a href="https://www.bundesbank.de/resource/blob/737278/458ccd8a8367fe8b36bbfb501b5404c9/mL/payment-behaviour-in-germany-in-2017-data.pdf">74% of all transactions in 2017 were performed using cash</a>. With a lot of restaurants, cafes and kebab shops having no options for cashless payments, Germans were used to carry a higher amount of cash in their wallets compared to their neighbours. With the pandemic coming about, the cashless transactions have been on the rise. Many stores had to overnight set up the options to pay with cards and mobile phones in order to protect their customers and employees. In a<a href="https://www.initiative-deutsche-zahlungssysteme.de/presse/pressemitteilungen/2020/24062020/"> survey</a> performed in April, over 57% of the respondents said they are using more card payments than in the past.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*dC4ap1SAIBzrha3E0SDxBw.jpeg" /></figure><p>Looking at this example and many others from our daily lives, it makes one question if there is a need to digitalize other sectors in order to prevent or reduce the impact on our lives in case of another global crisis.</p><p>One of the sector that is in great need to be digitalized is the electricity sector. As the sources of generation are slowly being changed from centralized fossil fuel-based power plants to decentralized energy resources (DERs) such as wind turbines and solar panels, the electricity sector has been seeing a lot of changes. Germany has been leading the way with <a href="https://www.energy-charts.de/energy_pie.htm?year=2019">46% of the total electricity generation</a> in 2019 came from renewable energy sources. But, the growing share of DERs also comes with its own set of problems.</p><p>Since a significant amount of DERs are weather dependent generators (wind turbines and solar panels), the peak generation of electricity does not always align with the consumption peak. These imbalances are larger in winter where the sunlight hours are minimal and winds are unreliable. Therefore, extensive electricity storage solutions would need to be added, or <a href="https://www.greenbiz.com/article/radical-idea-get-high-renewable-electric-grid-build-way-more-solar-and-wind-needed">the renewable capacity would need to be overbuilt</a>, or other fossil-based generators would need to be used to meet the peak electricity demand. Additionally, these generators stress the grid infrastructure that is required for the transportation of the electricity from the site of generation to consumption. With the rising share of renewables, the maintenance cost of the electricity grid is only going to increase.</p><p><em>As most countries are aiming to significantly increase the share of renewables in their electricity generation, these problems need to be addressed and other parts of the electricity ecosystem (transmission, distribution and retail) needs to evolve in order to manage the growing number of decentralized electricity generators.</em></p><p>‘<a href="https://www.bmwi.de/Redaktion/EN/Artikel/Energy/smart-grids.html">Smart grid</a>’ is a term often used to describe the electricity grid of the future and its many functions. There are a lot of technical solutions that were being researched under the smart grids banner for the last decade, but not a lot has changed for the end consumer. Other than installing solar panels on the rooftop slowly becoming an economical option, the interaction of the end customers with their electricity has not evolved. Every household needs to have a contract with an electricity provider who buys electricity on their behalf and charges them according to their yearly consumption. The only effort one might have to do is to send the analog meter (<a href="https://www.stromnetz.berlin/en/technology-innovations/how-does-a-meter-work">Ferraris meter</a>) reading once a year. So this brings up the question, what role do you, the end consumer, have in this revolution and why should you really care about it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_TyO2ciiiVS5jdHHiQ2eTA.jpeg" /><figcaption><a href="https://ieeexplore.ieee.org/document/7942504">Future electricity grid and its interactions in different sectors</a></figcaption></figure><p>There are a few good reasons for investing your time and energy in it.</p><h3>Higher degrees of autonomy</h3><p>The future electricity system relies on a hierarchal approach which promotes usage of electricity generated nearest to the location of consumption. With the help of<a href="https://en.wikipedia.org/wiki/Smart_meter"> smart meters</a>, it is possible to communicate electricity consumption and generation in near real-time. Therefore, it opens up the world for an end customer in ways never imagined before. Concepts such as <a href="http://www.cired.net/publications/workshop2018/pdfs/Submission%200272%20-%20Paper%20(ID-21042).pdf">Local Energy Markets (LEMs)</a>, <a href="https://en.wikipedia.org/wiki/Local_flexibility_markets">Local Flexibility Markets (LFMs)</a>, <a href="https://www.greencharge2020.eu/news/smart-charging-system-electric-vehicles/">Smart charging of electric vehicles</a>, <a href="https://www.umweltbundesamt.de/en/topics/climate-energy/renewable-energies/guarantees-of-origin-for-renewable-energy-sources#register-of-guarantees-of-origin-hknr">real-time power labelling</a>, <a href="https://irena.org/-/media/Files/IRENA/Agency/Topics/Innovation-and-Technology/IRENA_Landscape_Solution_11.pdf">Power-to-X solutions</a>, etc become possible and offer the end customer much more freedom to make decisions for their electricity needs.</p><h4>Pay what you actually value</h4><p>Since most of these smart grid solutions require higher participation from the end customer, the incentives need to be strong for people to change their behaviour. One of the big incentives is the potential of saving on the electricity bill. With solutions such as LEMs and LFMs, the whole process becomes more streamlined in terms of ease of access, transparency and reliability. The end customer pays exactly how much the electricity is currently valued when they trade with their neighbours in LEMs and receive compensation for changing your electricity requirements to help balance the grid. Additionally, as electricity from solar panels become cheaper around the world, the support schemes such as subsidies for installation and compensation for feeding in excess generation in the grid would be slowly removed. Therefore, for end customers that have or are planning to install solar panels on their rooftops have lower monetary incentives than before. With a lot of the smart grid solutions, these small scale electricity producers can get a better price for their excess generation in an open market and hence increase their share of savings on the electricity bill.</p><h4>Freedom to choose</h4><p>Another major benefit that has been identified for the end customer is to have a higher degree of control of their electricity-related interactions. Increase investment in your local community: buying electricity from your neighbours rather than large coal power plants hundreds of kilometres away, support the energy transition and contribute to the reduction of greenhouse gas emission by buying green electricity, influence your electricity consumption based on different market and technical factors, choose which reward scheme you would like to use to get compensated for the services you offer and decide how much you want to pay for your electricity.</p><h4>Why not have it all on your phone?</h4><p>Since the majority of services can be availed by a click on your phone, it only makes sense to transfer your electricity-related interactions also on your phone. Having an app with an appeasing user-interface that tells you all about how much electricity you are consuming or producing in real-time, your current monetary balance, how much carbon emission you saved by buying green electricity, the highlights about your electricity patterns based on the historical data, if any of your electric devices are consuming too much, and maybe even alert you if there is a spike in your electricity consumption while you are on your vacation, like a burglar alarm.</p><p>As electric vehicles become an attractive option; heating via electricity (<a href="https://www.iea.org/reports/heat-pumps">using heat pumps</a>) becomes common for household and the <a href="https://www.statista.com/statistics/678739/forecast-on-connected-devices-per-person/">network-connected devices</a> per person keep on <a href="https://www.iea-4e.org/document/429/total-energy-model-for-connected-devices">increasing</a>, the stress on the electricity grid is only going to increase along with the household electricity bills. Therefore, there is an even bigger need for these smart solutions to be implemented. A lot of research and development work still needs to be done to realise many of the proposed solutions. But there is a consensus among the researchers and the industry, that none of these solutions would be possible unless the end customers are brought on board.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68c475a8d4e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/why-should-you-care-about-the-digitalization-of-your-electricity-68c475a8d4e4">Why should you care about the digitalization of your electricity?</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building dApp’s Backend with Node.js and Webpack]]></title>
            <link>https://medium.com/oli-systems/building-dapps-backend-with-node-js-and-webpack-311cda224da5?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/311cda224da5</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 07:25:40 GMT</pubDate>
            <atom:updated>2022-02-08T21:43:27.850Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bootstrapping the dApp Development Experience</h4><h3>Building dApps with Node.js and Webpack</h3><h4>A step-by-step tutorial to building the back-end for Apps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*3rbdCZPZ86PXIyyRqLJ7nQ.png" /></figure><p>Blockchain is a relatively young technology that is under continuous development. Similarly, applications built on the top of the blockchain are also still growing. As a result, there are several tools and best practices to streamline the development process. This tutorial will guide you through the steps to build a node.js back-end for a Decentralized Application (dApp). The tutorial introduces different developer tools and best practices and demonstrates how can we use them to boost the development experience.</p><h3>The Big Picture</h3><p>A Decentralized Application (dApp) is a kind of web application whose back-end runs on a decentralized network such as Blockchain. The dApp has a traditional front-end built with HTML, CSS, and JavaScript. However, instead of connecting with a backend server, the dApp is connected to a blockchain node. The backend code of the dApp is written in the form of a smart contract using the Solidity programming language. The smart contract is a piece of program that contains the core logic of a dApp and is an integral part of the blockchain. The smart contracts are deployed using a locally running blockchain node and resides on the blockchain network.</p><p>The communication between the front-end and the back-end is done through a Web3 JavaScript library. The Web3 is a collection of libraries which contains functionality to interact with the Ethereum ecosystem. The communication is essentially involved reading and writing the data from the blockchain through the smart contracts. A Web3 provider can be set up in both the frontend and the backend to send the transaction and listen to the blockchain events.</p><h3>The Goal of the Tutorial</h3><p>The goal of the tutorial is to define a project structure to built a back-end for the dApp using node.js, truffle, and webpack. We will write a simple smart contract that will send some info to the blockchain and emit an event in the response of a successful transaction.</p><p>The back-end will perform two main functions:</p><ol><li>Publish transactions to the blockchain network</li><li>Listen to the blockchain events</li></ol><h3>Developer Tools</h3><p>We will make use of the following tools:</p><h4><a href="https://www.trufflesuite.com/">Truffle Framework</a></h4><p>We are using Truffle framework for the development of smart contracts. The Truffle provides a suite of tools to write smart contracts in Solidity, perform unit tests using Mocha and Chai, and deploy contracts on the Blockchain. Some of the most useful and frequently used truffle commands are:</p><ul><li>Compile — truffle compile</li><li>Migrate — truffle migrate</li><li>Test contracts — truffle test</li></ul><p>You can find more from the official <a href="http://www.truffleframework.com/docs">docs</a></p><h4><a href="https://www.trufflesuite.com/ganache">Ganache</a></h4><p>We will make use of ganache to set up a private blockchain for the smart contract development, testing, and to speed up the overall iteration process. Furthermore, ganache comes with a built-in block explorer to examine blocks, transactions, contracts, and events to gain insight about what’s happening under the hood.</p><h4><a href="https://www.npmjs.com/package/prettier-plugin-solidity">Solidity Prettier Plugin</a></h4><p>Solidity Prettier automatically formats the Solidity files according to a predefined style guide.</p><p>Using Solidity prettier in combination with Solhint is quite effective as the prettier automatically fix many of the errors that Solhint finds, such as indentation and code styles.</p><h4>Linter — <a href="https://protofire.github.io/solhint/">Solhint</a></h4><p>The Solhint is a great tool and library for the static analysis of Solidity code. Using Solhint will help us in automatic syntax checking and detect security vulnerabilities of the Solidity code.</p><p>Alternatively, you can use <a href="https://github.com/duaraghav8/Ethlint">Ethlint</a>.</p><h4>Truffle Unit Test</h4><p>We will use the truffle unit testing to test the core functionality of our smart contract. Under the hood, Truffle uses the Mocha testing framework and Chai assertion library to write the tests in JavaScript.</p><h4><a href="https://github.com/sc-forks/solidity-coverage">Solidity Code Coverage</a></h4><p>The Solidity coverage tool shows how much of the code-base has been covered and tested by the unit tests.</p><h4>Gas Cost Estimation</h4><p>We will use <a href="https://www.npmjs.com/package/eth-gas-reporter">ETH Gas Reporter</a> to calculate gas and cost for the execution of functions and contract deployment. The market price data is fetched from <a href="https://coinmarketcap.com/">Coin Market Cap</a> and gas price is fetched from <a href="https://ethgasstation.info/">Eth Gas Station</a>.</p><h3>Prerequisites</h3><p>Install the following dependencies globally:</p><ul><li><a href="https://www.trufflesuite.com/docs/truffle/getting-started/installation">Truffle</a> &gt;= v5.0.41 ($ npm i truffle -g)</li><li><a href="https://nodejs.org/en/download/">Node</a> &gt;= v10.16.3</li></ul><p>We will be using the <a href="https://www.coingecko.com/en/api">CoinGecko</a> free API to fetch the cryptocurrency prices.</p><h3>Project Structure</h3><p>We will start with creating a new empty project directory dApp-nodeJS-webpack and inside the directory, we will initiate a npm project.</p><ul><li>In your terminal type the following commands:</li></ul><pre>$ mkdir dApp-nodeJS-webpack &amp;&amp; cd $_<br>$ npm init</pre><p>This will create a package.json file that holds the metadata about the project such as project dependencies, purpose, version, and scripts, etc.</p><ul><li>Create a new file index.js in the root directory. This file will call the overall functionality of the app by requiring the other modules.</li></ul><pre>$ touch index.js</pre><p>Add the following log statement to the newly created file:</p><pre>console.log(&#39;Hello world!&#39;)</pre><ul><li>To execute the functionality from the index.js file, add the following command to the scripts section of package.json file:</li></ul><pre>&quot;scripts&quot;: {<br>    &quot;app&quot;: &quot;node index.js&quot;<br>  },</pre><p>Now open a terminal inside the root directory and type the following command:</p><pre>npm run app</pre><p>If you see the “Hello world!” in the console, you are good to go!</p><ul><li>Inside the root directory, create a new directory app and inside that initiate a truffle project:</li></ul><pre>$ mkdir app &amp;&amp; cd $_<br>$ truffle init</pre><p>The result will look like the following terminal output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb438ea82490e539f7c133a5acee105f/href">https://medium.com/media/fb438ea82490e539f7c133a5acee105f/href</a></iframe><p>At this point, your project should resemble to this GitHub <a href="https://github.com/olisystems/dApp-nodeJS-webpack/tree/0325ec125ccdbb8ae13f3925ad3c2ea01930430e">commit</a>.</p><h3>Smart Contract Development</h3><p>For the demo purpose, we are going to develop a simple Registration smart contract. The contract will allow the owner to register new users and only registered users will be able to send their values to the blockchain. Additionally, events will be emitted in the response of each successful transaction for user registration and send values.</p><h4>The Anatomy of the Smart Contract</h4><p>Let’s create a new file Registration.sol inside the contracts directory. The smart contract will start with specifying the version pragma. The pragma will specify the compiler version and is important to avoid the compatibility issues:</p><pre>pragma solidity &gt;=0.5.0 &lt;0.7.0;</pre><p>Next, we can start by defining the contract itself. The first state variable we have to declare is the address to store the Ethereum address of the contract owner. We have specified the visibility of the variable as public to let other contracts to access it. We will assign the deployer address to the owner using constructor. The constructor will be executed only once at the time when the contract is created.</p><pre>contract Registration {<br>    address public owner;</pre><pre>    constructor() public {<br>        owner = msg.sender;<br>    }<br>}</pre><p>We create a struct User that has a bunch of attributes with which we will register a user.</p><pre>struct User {<br>        string name;<br>        uint8 age;<br>        bool registered;<br>    }</pre><p>We will declare two events NewUser and NewValue. These events will be triggered once the functions registerUser and send are executed, respectively.</p><pre>event NewUser(address userAddress, string name, uint8 age);<br>event NewValue(address userAddress, uint256 value);</pre><p>The contract will use a mapping users to assign Ethereum address to User struct.</p><pre>mapping(address =&gt; User) public users;</pre><p>We define a modifier onlyOwner to check if the function executes as expected or not. The use of onlyOwner modifier will allow only owner of the contract to register the new user.</p><pre>modifier onlyOwner {<br>        require(msg.sender == owner, &quot;Only owner can register a user.&quot;);<br>        _;<br>    }</pre><p>The contract contains two functions, registerUser and send. The registerUser will register a new user with the information specified in the User struct and bind the Ethereum address of the user with the struct. An event NewUser will be emitted if the function execution goes successful.</p><pre>function registerUser(<br>        address _address,<br>        string memory _name,<br>        uint8 _age<br>    ) public onlyOwner {<br>        users[_address] = User(_name, _age, true);<br>        emit NewUser(_address, _name, _age);<br>    }</pre><p>The send function will allow only registered users to send some random values to the blockchain by emitting an event on a successful transaction.</p><pre>function send(uint256 _value) public {<br>        require(<br>            users[msg.sender].registered == true,<br>            &quot;Caller is not registered.&quot;<br>        );<br>        emit NewValue(msg.sender, _value);<br>    }</pre><h4>Solidity Linting and Prettier</h4><p>To boost the smart contract development experience, we will use Solidity linting and prettier tools. For dependency management, we will use node and npm. To do that, we will init a npm project inside the app directory using the command npm init. After that run the following command to install the solhint, prettier and prettier-plugin-solidity:</p><pre>$ npm install solhint --save-dev<br>$ npm install --save-dev prettier prettier-plugin-solidity</pre><p>Next, we need to add the following script to package.json file located inside the app directory to run the prettier on all the contracts inside the contracts directory:</p><pre>&quot;prettier&quot;: &quot;prettier --write **/*.sol&quot;</pre><p>After that, run the following command to apply prettier to our smart contracts:</p><pre>$ npm run prettier</pre><p>The output will look like the following:</p><pre>&gt; prettier --write **/*.sol</pre><pre>contracts/Migrations.sol 246ms<br>contracts/Registration.sol 199ms</pre><p>For linting, we can use a .solhint.json file to configure Solhint linter for the whole project. Type the following command to generate a sample .solhint.json file:</p><pre>$ npx solhint --init</pre><p>Populate the newly created JSON file with the following rulesets:</p><pre>{<br>&quot;extends&quot;: &quot;solhint:recommended&quot;,<br>&quot;plugins&quot;: [],<br>&quot;rules&quot;: {<br>    &quot;avoid-suicide&quot;: &quot;error&quot;,<br>    &quot;avoid-sha3&quot;: &quot;warn&quot;<br>}<br>}</pre><p>Finally, add the following script to the package.json file:</p><pre>&quot;slint&quot;: &quot;solhint \&quot;contracts/**/*.sol\&quot;&quot;</pre><p>Run the following command to apply the linting:</p><pre>$ npm run slint</pre><p>The output of the above will look be like this:</p><pre>&gt; solhint &quot;contracts/**/*.sol&quot;<br></pre><pre>contracts/Migrations.sol<br>  6:20  warning  Variable name must be in mixedCase  var-name-mixedcase</pre><pre>✖ 1 problem (0 errors, 1 warning)</pre><h3>Truffle Unit Tests</h3><p>Unit tests are an integral part of the development to test if a smart contract works as expected or not. We will write a truffle unit test in JavaScript. Under the hood, truffle uses <a href="https://mochajs.org/">Mocha</a> testing framework and <a href="https://www.chaijs.com/">Chai</a> assertion library. We will also use some additional assertions and utilities, especially for testing the events, by using <a href="https://www.npmjs.com/package/truffle-assertions">truffle-assertions</a> package.</p><p>We will start by creating an empty JavaScript file registration.js inside the test directory.</p><ul><li>Install the truffle-assertion library and include this, along with contract artifacts, in the registration.js test file:</li></ul><pre>$ npm i truffle-assertions --save-dev</pre><p>and inside the test file, include these line:</p><pre>const Registration = artifacts.require(&#39;Registration&#39;)<br>const truffleAssert = require(&#39;truffle-assertions&#39;)</pre><ul><li>Create basic layout of the test file as given below:</li></ul><pre>contract(&#39;Registration&#39;, (accounts) =&gt; {</pre><pre>})</pre><ul><li>We will set up some test variable and create a global instance of our smart contract before executing the tests:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941e706bf8c084b0ab84cd31d3f99e1d/href">https://medium.com/media/941e706bf8c084b0ab84cd31d3f99e1d/href</a></iframe><ul><li>Next, we will test the following functionality of the contract:</li><li>registerUser function should be executed only by the owner and it should emit the NewUser event:</li></ul><pre>it(&#39;should register a new user&#39;, async () =&gt; {<br>    let result = await contract.registerUser(user, name, age, {<br>        from: owner,<br>    })<br>    // test event<br>    truffleAssert.eventEmitted(result, &#39;NewUser&#39;, (ev) =&gt; {<br>        return ev.userAddress == user &amp;&amp; ev.name == name &amp;&amp; ev.age == age<br>    })<br>})</pre><ul><li>The registerUser function should fail if caller is not the owner:</li></ul><pre>it(&#39;should fail to register by non-owner&#39;, async () =&gt; {<br>    await truffleAssert.reverts(<br>        contract.registerUser(user, name, age, {<br>        from: notOwner,<br>        }),<br>    )<br>})</pre><ul><li>A registered user should be able to call the send function:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc9a49298844b0ba4b92ae0145dc4588/href">https://medium.com/media/cc9a49298844b0ba4b92ae0145dc4588/href</a></iframe><ul><li>An un-registered user should not allow to call the send function:</li></ul><pre>it(&#39;should fail to send value from un-registered user&#39;, async () =&gt; {<br>    await truffleAssert.reverts(<br>        contract.send(value, {<br>        from: unregistered,<br>        }),<br>    )<br>})</pre><h4>Writing Migrations</h4><p>Create a new file 2_deploy_contracts.js inside the migrations directory and add the following contents to it:</p><pre>const Registration = artifacts.require(&#39;Registration&#39;)</pre><pre>module.exports = function (deployer) {<br>  deployer.deploy(Registration)<br>}</pre><p>The above migration is short and clean. However, we will look another way to export the contract ADDRESS and ABI during the migration so that we can use this metadata later to create a contract instance. This is useful especially in the case while calling the contract methods.</p><p>Add the following code block to the migrations file and it will create a Metadata.js file in the src directory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fe6df24eb281f44d4bd0be382e7c616/href">https://medium.com/media/7fe6df24eb281f44d4bd0be382e7c616/href</a></iframe><h4>Config Development Network</h4><ul><li>Uncomment following lines inside the truffle-config.js file to set up a local development network:</li></ul><pre>// development: {<br>//  host: &quot;127.0.0.1&quot;,     // Localhost (default: none)<br>//  port: 8545,            // Standard Ethereum port (default: none)<br>//  network_id: &quot;*&quot;,       // Any network (default: none)<br>// },</pre><ul><li>We need to install and run <a href="https://github.com/trufflesuite/ganache-cli">ganache-cli</a> before executing the tests. Run the following command to install the ganache-cli as a development dependency:</li></ul><pre>$ npm i ganache-cli --save-dev</pre><p>and then add the following scripts to the package.json file to run the ganache and test through npm:</p><pre>&quot;ganache&quot;: &quot;ganache-cli -m &#39;electric gift gold bitter boring surface stumble swift peanut adult horse dish&#39;&quot;,<br>&quot;test&quot;: &quot;truffle test&quot;</pre><ul><li>Now open two terminals inside the app directory and then first run the ganache-cli:</li></ul><pre>$ npm run ganache</pre><p>In the second terminal, run the test file:</p><pre>$ npm run test</pre><p>The result of the above command should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d2e6c0d089edc17f0e79d3c548a18e/href">https://medium.com/media/41d2e6c0d089edc17f0e79d3c548a18e/href</a></iframe><h4>Solidity Code Coverage</h4><p>Install the Solidity code coverage:</p><pre>$ npm install --save-dev solidity-coverage</pre><p>and add this to the plugin array of truffle-config.js file:</p><pre>module.exports = {<br>  networks: {...},<br>  plugins: [&quot;solidity-coverage&quot;]<br>}</pre><p>Add the following script to scripts in the package.json file:</p><pre>&quot;coverage&quot;: &quot;truffle run coverage&quot;</pre><p>Finally, run the command:</p><pre>$ npm run coverage</pre><p>The output will contain the following code coverage metrics:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c35f8aa399d6a00d68c7bf40e6b7580/href">https://medium.com/media/6c35f8aa399d6a00d68c7bf40e6b7580/href</a></iframe><h4>Eth Gas Reporter</h4><p>Install the Eth gas reporter by running the following command:</p><pre>$ npm install --save-dev eth-gas-reporter</pre><p>config the reporter in the truffle-config.js file as:</p><pre>mocha: {<br>    // timeout: 100000<br>    reporter: &#39;eth-gas-reporter&#39;,<br>    reporterOptions: {<br>        excludeContracts: [&#39;Migrations&#39;],<br>    },<br>},</pre><p>Now again run the npm run test command and the output will be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71dd1128fee348c6a688b6e3353089ae/href">https://medium.com/media/71dd1128fee348c6a688b6e3353089ae/href</a></iframe><p>At this point, your project may look like to this GitHub <a href="https://github.com/olisystems/dApp-nodeJS-webpack/tree/e35cfddf93721954b0d9b31e6f90f748521a1b01">commit</a>.</p><h3>Backend Development</h3><p>The back-end of the application is developed as a Node.js application. The application is developed using the JavaScript class and ES6syntax. The following snippet shows the node.js modules developed for the back-end.</p><h4>Deploy Contract</h4><p>Run the following command inside the app directory:</p><pre>truffle migrate --reset --compile-all</pre><p>The above command will generate the Metadata.js file in the src directory. The contains contract ADDRESS and ABI.</p><h4>Modules</h4><p>Let’s create another directory src inside the app directory that will serve as a container for our modules. The backend will contain the following modules:</p><ul><li>Provider: A web3 provider is required to set up a connection with an Ethereum node, create the instance of the contract, and to call the methods from the smart contract. For that, install web3 as project dependency by running the following command:</li></ul><pre>$ npm install web3</pre><p>Create a new file Provider.js and add the following code block to that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3ec0f80db6255de69037c5dcfd087d3/href">https://medium.com/media/e3ec0f80db6255de69037c5dcfd087d3/href</a></iframe><ul><li>Contract.js: This module will return the instance of the smart contract. Create and add the following block of code to Contract.js file:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffd96dca08634280b250b538070e270b/href">https://medium.com/media/ffd96dca08634280b250b538070e270b/href</a></iframe><ul><li>Methods: This module will contain the functions to call the methods from the smart contract. For the demo purpose, we will call the sendmethod at a 30 seconds time interval. The contents of Methods.js will look like the following:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cea5e5d41026648819ccb6105c7fe7f4/href">https://medium.com/media/cea5e5d41026648819ccb6105c7fe7f4/href</a></iframe><ul><li>index.js: Finally, call the contract methods from the index.js file:</li></ul><pre>const Registration = require(&#39;./app/src/Methods&#39;)<br>const registration = new Registration()<br>registration.registerUser()<br>registration.sendDataInterval()</pre><p>Let’s open a terminal inside the root directory and run the following command:</p><pre>npm run app</pre><p>As a result, you should see the transaction hash in the console.</p><p>The complete code can be found <a href="https://github.com/olisystems/dApp-nodeJS-webpack/tree/3960541a294b236e52eb05c1d4db09feb0a23f15">here</a>.</p><h3>Webpack Integration</h3><p>A webpack is a static modular bundler which treats all files and assets as modules and relies on a dependency graph. Using the dependency graph, webpack statistically traverses all modules and their dependencies to build the graph and finally generate a single JavaScipt file that contains code from all modules in the correct order.</p><h4>Webpack Main Points</h4><p>To integrate webpack into the project, let’s have a brief look at the main points of the webpack:</p><ul><li>Entry: This is the module that webpack uses to start building its internal dependency graph. From this module, webpack determines all other modules and libraries for the entry module and includes them in the graph until no dependency is left. For the current project, the entry point is index.js file</li><li>Output: This property defines a location where webpack will generate the bundle and a name for the bundle file.</li><li>Loaders: This is the property that webpack uses to transform the source code of non-JavaScript modules before they are added to the dependency graph.</li><li>Plugins: Plugins are helpful to do the tasks that loaders can’t do such as asset management, bundle minimization, and optimization, etc.</li><li>Mode: Mode property specifies built-in optimizations corresponding to each environment such as production, development, or none.</li></ul><h4>Webpack Configurations</h4><p>Webpack uses a special configuration file, webpack.config.js, that specifies how assets and files will be transformed to generate the specified output. From the configurations, the webpack starts from the entry point and resolves each module it encounters while building the dependency graph. The final output will be a small bundle of all the modules of the project.</p><p>First, we need to install webpack and webpack-cli as project dependency. Run the following command inside the root directory of the project:</p><pre>$ npm install webpack webpack-cli --save-dev</pre><p>In the package.json file, we can create webpack tasks in the scripts section as follows:</p><pre>&quot;dev&quot;: &quot;webpack --mode development&quot;,<br>&quot;build&quot;: &quot;webpack --mode production&quot;</pre><p>In the above scripts, we have used --mode flag to create development and production builds. Finally, add the following minimum configurations to the webpack.config.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaaffcb3b9e8ce9a6b4402de9cbee19f/href">https://medium.com/media/aaaffcb3b9e8ce9a6b4402de9cbee19f/href</a></iframe><p>Run the $ npm run dev command inside the root directory and notices dist directory as a result. Change the directory to dist and run the bundle using the following command:</p><pre>$ node bundle.js</pre><p>Make sure you have ganache running and the artifacts are updated. If you could see the same output as before (transaction hashes), congratulations! you are all done🎉🎉🎉</p><p>Let’s tweak some more configurations to make the development experience a breeze.</p><ul><li>Add watch flag to enable hot reload every time a file change. Change the dev script from</li></ul><pre>&quot;dev&quot;: &quot;webpack --mode development&quot;,</pre><p>to</p><pre>&quot;dev&quot;: &quot;webpack --mode development --w&quot;,</pre><ul><li>Clean the dist folder before each build. For this, we need to install and configure the clean-webpack-plugin by using the following command:</li></ul><pre>$ npm install --save-dev clean-webpack-plugin</pre><p>Update the webpack.config.js by adding the following lines:</p><pre>const { CleanWebpackPlugin } = require(&#39;clean-webpack-plugin&#39;);</pre><pre>// other config, removed for brevity</pre><pre>plugins: [<br>  new CleanWebpackPlugin()<br>],</pre><p>The complete project code can be found <a href="https://github.com/olisystems/dApp-nodeJS-webpack.git">here</a>.</p><p>Happy coding🎉🎉🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311cda224da5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/building-dapps-backend-with-node-js-and-webpack-311cda224da5">Building dApp’s Backend with Node.js and Webpack</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Joy of Building Snaps for Python Applications]]></title>
            <link>https://medium.com/oli-systems/the-joy-of-building-snaps-for-python-applications-4fa35c36b1a3?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/4fa35c36b1a3</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[snapcraft]]></category>
            <category><![CDATA[snap]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 10:33:17 GMT</pubDate>
            <atom:updated>2020-06-01T10:33:17.129Z</atom:updated>
            <content:encoded><![CDATA[<h4>ADVANCED SNAP USAGE</h4><h4>A tutorial for inter-snap communication using the content interface</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwewhQVyIenFiqjEixAGEg.png" /><figcaption>Source: <a href="https://snapcraft.io/store">https://snapcraft.io</a></figcaption></figure><p>While building applications in Python, we have to deal with dependency management that is not easy especially when it comes to package and ship your app. A snap bundles an application and all its dependencies to work across a range of Linux distributions. Snaps can be found and installed from the <a href="https://snapcraft.io/store">snap store</a>.</p><p>In this tutorial, We will create two snaps to persist the user config data and then share this data with a <em>consumer</em> snap. The applications are developed in Python, the source code can be found <a href="https://github.com/olisystems/intersnap-com-demo">here</a>.</p><ul><li>writer snap that will persist user config data to $SNAP_DATA</li><li>reader snap that will read the config data file created by the writer snap</li></ul><p>This tutorial has been written using Ubuntu 20.04 LTS and it should work without modifications for other Ubuntu releases (18.04 LTS, 19.10 LTS). The tutorial aims to give an overview of building snaps and their advanced usage. We will use a command-line tool, called Snapcraft, for building snap which reads the snap metadata from a declarative file and runs the build.</p><h3>Prerequisites</h3><p>We need to install snap and snapcraft before we start building snaps.</p><h3>Install Snap on Ubuntu</h3><p>For Ubuntu 16.04 LTS (Xenial Xerus) and later, snap is pre-installed and ready to go. However, use the following commands to install the snap if it is not already installed:</p><pre>sudo apt update<br>sudo apt install snapd</pre><p>Type the following command to make sure that snap is correctly installed:</p><pre>snap --version</pre><p>You should see an output similar to this:</p><pre>snap    2.44.3+20.04<br>snapd   2.44.3+20.04<br>series  16<br>ubuntu  20.04<br>kernel  5.4.0-33-generic</pre><h3>Install Snapcraft</h3><p>Next, we need to install Snapcraft command-line tool for building snaps by running the following command in the terminal:</p><pre>sudo snap install --classic snapcraft</pre><h3>Process of Building a Snap</h3><p>The process of building a snap can be divided into four steps:</p><ol><li>List snap’s requirements</li><li>Initializing snap environment</li><li>Add interfaces to snap</li><li>Create snap</li><li>Publish and share</li></ol><h3>List Snap’s Requirements</h3><p>Usually, the requirements of a snap are the same as the requirements of the application itself. The <a href="https://github.com/olisystems/intersnap-com-demo/tree/master/writer-snap">writer</a> app has the functionality to take user input using a Python package called <a href="https://click.palletsprojects.com/en/7.x/">click</a> and then persist this input into a toml file.</p><p>The requirements for the <a href="https://github.com/olisystems/intersnap-com-demo/tree/master/reader-snap">reader</a> snap are pretty much simple, it has to read the configs saved by writer app and print them to console.</p><p>As both of our apps are fairly simple, I’ll skip the app development process for now. Once we have developed our apps, next is to initialize the snap environment.</p><h3>Initializing snap environment</h3><p>Initializing a snap environment involves creating a snapcraft.yaml file that provides metadata for the snap. Initialize the snap environment by typing the following command in the root writer-snap:</p><pre>snapcraft init</pre><p>The result of the above command is a snapcraft.yaml template with <a href="https://snapcraft.io/docs/adding-global-metadata">mandatory snap&#39;s metadata</a> inside the snap sub-directory.</p><p>Let’s add some necessary <a href="https://snapcraft.io/docs/adding-parts">parts</a> to describe our application.</p><ol><li>The first section in the parts describes the source and plugin definition.</li></ol><pre>[...]<br>parts:<br>  writer-snap:<br>    source: .<br>    plugin: python<br>    requirements: [&#39;requirements.txt&#39;]</pre><p>Note: [...] represents the rest part of the code.</p><p>In the above code snippet, writer-snap is the arbitrary part name. Next is the source for which has specified the current repository. Other options for the source could be git or a tarball. We are using Python plugin that reads app requirements from the requirements.txt file located in the root of the project.</p><ol><li>In our app, we want to create a config.toml file if it does not exist already and then write configs to this file. To do that, we will create the following <a href="https://github.com/olisystems/intersnap-com-demo/blob/master/writer-snap/writer.sh">wrapper script</a> in the root directory of our project:</li></ol><pre>#! /bin/sh</pre><pre>[ -e &quot;$SNAP_DATA/config.toml&quot; ] || touch $SNAP_DATA/config.toml</pre><pre>exec &quot;$@&quot;</pre><p>Now we need to make this script executable and then ship it in bin/. Run the following command in the root of the project:</p><pre>sudo chmod +x writer.sh</pre><ol><li>To ship executable script to the bin/, we will add the following part in parts:</li></ol><pre>[...]<br>  launcher:<br>    plugin: nil<br>    source: .<br>    override-build: |<br>      mkdir -p $SNAPCRAFT_PART_INSTALL/bin<br>      cp -av writer.sh $SNAPCRAFT_PART_INSTALL/bin/</pre><p>The above part will create a directory $SNAPCRAFT_PART_INSTALL/bin and copy the writer.sh script over there.</p><ol><li>Finally, we need to change the <a href="https://snapcraft.io/docs/defining-a-command">command</a> entry in the apps section as follows:</li></ol><pre>[...]<br>apps:<br>  writer-snap:<br>    command: writer.sh writer-snap</pre><h3>Add Interface to Snap</h3><p>To share data between the snaps, we are going to use the <a href="https://snapcraft.io/docs/content-interface">content interface</a>. The content interface makes it possible to share data from a producer snap to one or more consumer snaps. The sharing of data happens at the filesystem level including executables, libraries, data files, and sockets also.</p><p>Add the following content slot to the snapcraft.yaml file:</p><pre>[...]<br>slots:<br>  shared-files:<br>    interface: content<br>    content: shared-files<br>    read:<br>      - $SNAP_DATA</pre><p>The content attribute describes the content and this attribute must be the same on both sides to establish the connection. The read attribute declares which part should be read by the reader snap.</p><p>The complete snapcraft.yaml file for the writer snap can be found <a href="https://github.com/olisystems/intersnap-com-demo/blob/master/writer-snap/snap/snapcraft.yaml">here</a>.</p><h4>Creating .yaml file for Reader Snap</h4><p>Creating the snapcraft.yaml file for the <a href="https://github.com/olisystems/intersnap-com-demo/tree/master/reader-snap">reader</a> snap is relatively simple as it will just read the configs. Repeat the aforementioned steps, except launcher part, for reader snap as well and add the content plug to the reader&#39;s snapcraft.yamlfile as follows:</p><pre>plugs:<br>  shared-files:<br>    interface: content<br>    content: shared-files<br>    target: $SNAP_DATA</pre><h3>Build Writer Snap</h3><p>Once we are done with the yaml file, it is time to create the snap. We will start creating the snap by running the following command with debug mode in the root of writer-snap:</p><pre>snapcraft --debug</pre><p>The output of the above command will look like this:</p><pre>[...]<br>Building writer-snap-data<br>Staging launcher<br>Staging writer-snap<br>Staging writer-snap-data<br>Priming launcher<br>Priming writer-snap<br>Priming writer-snap-data<br>Snapping &#39;writer-snap&#39; |<br>Snapped writer-snap_0.1dev_amd64.snap</pre><p>Congratulations! we have just created our first snap🎉🎉🎉🎉🎉🎉🎉🎉.</p><p>Note: When you run the command for the first time, you may prompt to install the multipass.</p><p>The newly created snap can be installed with the following command in the dev mode:</p><pre>sudo snap install writer-snap_0.1dev_amd64.snap --devmode</pre><p>The output will be like:</p><pre>writer-snap 0.1dev installed</pre><p>Finally, run the snap with the following command:</p><pre>sudo writer-snap</pre><p>Note: You can just hit enter to save the default configs without typing anything.</p><p>Additionally, you can run the following command to see info about the installed snap:</p><pre>snap list writer-snap</pre><p>The output should look like:</p><pre>Name         Version  Rev  Tracking  Publisher  Notes<br>writer-snap  0.1dev   x1   -         -          devmode</pre><p>You can check the contents of the config file with the following command:</p><pre>sudo nano /var/snap/writer-snap/x1/config.toml</pre><h4>Create Reader Snap</h4><p>To create the reader snap, repeat the above-described process.</p><p>Once the reader snap is created and installed, we need to make a connection between the writer and the reader snap.</p><p>To make a connection, use the following syntax:</p><pre>snap connect &lt;snap&gt;:&lt;plug interface&gt; &lt;snap&gt;:&lt;slot interface&gt;</pre><p>In our case the command will be:</p><pre>snap connect reader-snap:shared-files writer-snap:shared-files</pre><p>After establishing the connection, run the following command:</p><pre>reader-snap</pre><p>The output should look like:</p><pre>dict_items([<br>  (&quot;title&quot;, &quot;Building Python Snaps&quot;),<br>  (&quot;mqtt_connection&quot;,<br>  {<br>    mqtt_broker_ip: &quot;unbelievable-politician.cloudmqtt.com&quot;,<br>    mqtt_broker_port: &quot;8883&quot;,<br>    ssl_cert_path: &quot;ca-certificates.crt&quot;,<br>    mqtt_username: &quot;username&quot;,<br>  }),<br>]);</pre><p>To disconnect an interface, use snap disconnect:</p><pre>snap disconnect &lt;snap&gt;:&lt;plug interface&gt; &lt;snap&gt;:&lt;slot interface&gt;</pre><h3>Publish Snap</h3><p>Publishing the application to the snap store can be done in three steps:</p><ol><li>Create a developer account on <a href="https://login.ubuntu.com/v4apP4ET6CxsCIHS/+decide">the dashboard</a></li><li>Register application’s name on <a href="https://dashboard.snapcraft.io/register-snap/">dashboard.snapcraft.io</a></li><li>Upload your application</li></ol><h3>References</h3><p><a href="https://snapcraft.io/docs/python-apps">https://snapcraft.io/docs/python-apps</a></p><p><a href="https://ubuntu.com/tutorials/create-your-first-snap#1-overview">https://ubuntu.com/tutorials/create-your-first-snap#1-overview</a></p><p><a href="https://forum.snapcraft.io/t/how-to-persist-user-config-data-to-snap-user-data/15464">https://forum.snapcraft.io/t/how-to-persist-user-config-data-to-snap-user-data/15464</a></p><p><a href="https://www.youtube.com/watch?v=BEp_l2oUcD8&amp;feature=emb_logo">https://www.youtube.com/watch?v=BEp_l2oUcD8&amp;feature=emb_logo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fa35c36b1a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/the-joy-of-building-snaps-for-python-applications-4fa35c36b1a3">The Joy of Building Snaps for Python Applications</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test Driven Solidity with Truffle]]></title>
            <link>https://medium.com/oli-systems/test-driven-solidity-with-truffle-e4beaa2bd194?source=rss----9322226ecf04---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4beaa2bd194</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[truffle]]></category>
            <dc:creator><![CDATA[Muhammad Yahya]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 09:29:32 GMT</pubDate>
            <atom:updated>2019-08-09T08:45:53.359Z</atom:updated>
            <content:encoded><![CDATA[<h4>A BEGINNER FRIENDLY TUTORIAL</h4><h4>Unit-Testing of Smart Contracts with Truffle, Ganache, Mocha, and Chai</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MGEwZxuZSlQ2nIGB13uOxQ.jpeg" /></figure><h3>Introduction</h3><p>It is very common to write and compile Solidity code manually which is fine for small projects. However, as our project is growing bigger and bigger, it is good to have an automatic way of smart contracts development. In addition, testing Solidity code is crucial to avoid any problematic situation caused by a bug in the smart contract. There are different frameworks available for taking care of the development process. Truffle is one of them and is often regarded as the Ethereum Swiss Knife framework as it is a development environment, testing framework and asset pipeline for Ethereum.</p><h3>Objectives</h3><p>This tutorial is aimed to get started with Truffle and write some tests to check the basic features offered by Solidity.</p><ol><li>Create a truffle project and configure a development network</li><li>Create and deploy smart contracts</li><li>Interact with the smart contract from Truffle console</li><li>Write tests for testing main features offered by Solidity</li></ol><h3>Prerequisites</h3><ol><li><a href="https://nodejs.org/en/">Download </a>and install node.js</li><li>Install Truffle globally: <br>In order to install truffle globally on your machine, open a terminal and run this command<br>$ npm install truffle -g</li><li>Install ganache-cli:<br><a href="https://truffleframework.com/ganache">Ganache </a>is a personal and local blockchain for Ethereum development and provides a very good environment to deploy smart contracts and run tests. Ganache is available as a desktop application as well as a command line tool. In this tutorial, we are going to install ganache as a command line tool by running the following command in the terminal:<br>$ npm install ganache-cli -g</li></ol><h3>1. Creating a Truffle Project</h3><p>In the next few lines of code, we are going to create a directory and initialize it with Truffle to create a basic project skeleton.</p><pre>$ mkdir truffle-demo</pre><pre>$ cd truffle-demo</pre><pre>$ truffle init</pre><p>On successful initialization, we will see the following message in the console:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ba0aa2d334d5b2b0e874acab74bc10/href">https://medium.com/media/01ba0aa2d334d5b2b0e874acab74bc10/href</a></iframe><p>If we look at the newly created directory, Truffle has created a boilerplate file structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e930de8440546129a4d97751658d25f/href">https://medium.com/media/9e930de8440546129a4d97751658d25f/href</a></iframe><p>Let’s have a brief walk through of these files and folders:</p><h4>truffle.js</h4><p>This is the configuration file that contains information such as development network settings for the project. This file will be used to configure the development network.</p><h4>truffle-config.js</h4><p>This is the same file as truffle.js and used in case of windows system run into a conflict problem while executing the generic Truffle commands. So, in that case, this file will be used instead of truffle.js file.</p><h4>contracts</h4><p>This folder is a container for all of our smart contracts. Truffle goes to the contracts folder and looks for the compatible files ( .sol ) to compile while compiling the project. The folder already contains a Migrations.sol file.</p><h4>migrations</h4><p>The configurations for migrating the contract over the network are written in a JavaScript file. These settings basically define how (for example: in what order) smart contracts will be deployed over the blockchain. All those migration files will go inside the migration folder. This folder contains a file 1_initial_migration.js that will deploy the Migrations.sol contract to the blockchain.</p><h4>test</h4><p>All the tests — either written in Solidity or JavaScript — will go to this folder.</p><p>In addition, Truffle will create a build folder to hold artifacts of the compiled contracts. We will see this folder when we run $ truffle compile command but before that, we need to set up our private network first.</p><h3>2. Preparing the Test Environment</h3><p>After having installed ganache-cli, open a terminal and run</p><pre>$ ganache-cli</pre><p>Ganache has created ten accounts with some amount of ether for executing the development tasks. It also opens the RPC port 8545at localhost.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81166119edb74b83adda9ffaa448a9aa/href">https://medium.com/media/81166119edb74b83adda9ffaa448a9aa/href</a></iframe><p>Next, we need to configure network settings in truffle.js file as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e724d57bb7b1f7ff4b4d94ea3b3a4b0/href">https://medium.com/media/1e724d57bb7b1f7ff4b4d94ea3b3a4b0/href</a></iframe><p>In these lines of code, we have configured a single development network running on 127.0.0.1:8545.</p><ul><li>Line 2 defines an object which is keyed by a network name that is development in this case.</li><li>On the next lines, hostand port parameters of the network are configured.</li><li>Line 6 gives a development network that matches any network it connects to.</li></ul><p>So far we have initiated our truffle project, set up private network and ganache-cli running. In order to check if everything is set up correctly, type:</p><pre>$ truffle test</pre><p>We will see the following output:</p><pre>Compiling .\contracts\Migrations.sol...</pre><pre>0 passing (1ms)</pre><p>Now we are good to go!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxHMIDAy1qkzNS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxHMIDAy1qkzNS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxHMIDAy1qkzNS%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="321" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd7bfc47a16c80fbc4a0e131ef54beb/href">https://medium.com/media/3fd7bfc47a16c80fbc4a0e131ef54beb/href</a></iframe><h3>3. Smart Contract Development with Truffle</h3><p>The general workflow for smart contract development with Truffle can be accomplished with the following steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nghO1qNCy_N4HI5uLdtHpA.png" /></figure><h4>Writing the Smart Contract</h4><p>Let’s create a simple smart contract by typing the following command in the terminal:</p><pre>$ truffle create contract SimpleContract</pre><p>In the contracts folder, Truffle has just created SimpleContract.sol file with the smart contract boilerplate. Let’s populate this file with a bit of Solidity code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dd867be3726c1f3646866a30264a0c6/href">https://medium.com/media/9dd867be3726c1f3646866a30264a0c6/href</a></iframe><p>We have just created a SimpleContractwhich contains a constructor, a getterand a settermethod.</p><ul><li>Line 1 specifies the version pragma for Solidity compiler.</li><li>Line 3 defines the name of the contract.</li><li>Line 4 declares a public string variable name.</li><li>Line 6 uses the constructor function, that means this function will be automatically executed once when the smart contract is created. In this case, the value of the above declared variable name will be set to <em>‘my name’</em> when the contract is created.</li><li>Line 10 is the getter function that will return the value of name. By default, The compiler automatically creates getter functions for all public state variables. However, for the sake of understanding, I have just created a getter function here.</li><li>Line 14 defines another function to change the value of our name variable.</li></ul><p>This is a very simple smart contract with constructor, one getter and one setter function. In the next step, we will compile this contract.</p><h4>Compile the Smart Contract</h4><p>In order to compile the smart contracts, run the following command:</p><pre>$ truffle compile</pre><p>This will compile all the smart contracts from the contracts folder and create artifacts in the contracts folder of the newly created build directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d24e18dba225dcbd79e905851a5eb8e/href">https://medium.com/media/4d24e18dba225dcbd79e905851a5eb8e/href</a></iframe><p>If we open the contract folder file from the build directory, we can see that these files are the abstraction of smart contracts and contain the following information:</p><ul><li>contract name</li><li>ABI (a list of all functions along with their parameter and return values)</li><li>bytecode</li><li>deployed bytecode</li><li>compiler name and version</li><li>A list of networks onto which the contract has been deployed (once the contract is deployed)</li><li>address of the contract with respect to each network the contract is deployed to (once the contract is deployed)</li></ul><p>These are .json files and act as a JavaScript wrapper to interact with the respective smart contracts.</p><h4>Writing Migrations</h4><p>In order to deploy smart contract over the blockchain, we first need to write the configurations for migration in a JavaScript file. These files are basically responsible for staging the deployment tasks of smart contracts over the blockchain. But, to deploy the smart contracts with migrations we need to access their artifacts which were created as a result of truffle compile command.</p><p>In order to create a migration file, run the following command in the terminal:</p><pre>$ truffle create migration deploy_sample_contract</pre><p>If you go to the migrations folder, you will see a JavaScript migration file is created which is prefixed by a random number and suffixed by a description. This is because the history of previously run migrations is recorded on the blockchain and truffle migrate will start execution from the last run migration. The numbered prefixed is required and is used to record either a migration has been run successfully or not. Open the newly created file in text editor and change the contents as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecfc30fbe2cfabca8d70d5abc07da5f7/href">https://medium.com/media/ecfc30fbe2cfabca8d70d5abc07da5f7/href</a></iframe><ul><li>In line 1, we are specifying which contract is going to use for interaction using artifacts.require()method. This method is similar to node.js require method. However, it will return a contract abstraction that will be used for the rest of the deployment script. The important thing here is we have to pass the name of the contract definition and not the name of .sol file. Because a source file may contain more than one contracts.</li><li>At line 3, module.export() is used to export the migrations. This method export a function which accepts a deployer object as its first parameter. The deployer object is the main interface for staging the deployment tasks and has many functions available to simplify migrations. At line 5, we are using deploy method from deployer in order to deploy our SimpleContract.</li></ul><p>After writing the artifacts, make sure that ganache-cli is running in the background and run:</p><pre>$ truffle migrate</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54fb3c3557bd8bdf7141138aa1dfa131/href">https://medium.com/media/54fb3c3557bd8bdf7141138aa1dfa131/href</a></iframe><p>Here we can see the address (SimpleContract: 0x4f5c2b6471915398132b627fad0f3089ea5ddd05) where our contract is deployed.</p><h4>Interacting with the Smart Contract</h4><p>As we now have the address of our deployed contract, we directly interact it using the truffle console. Run truffle console to open the console in the terminal:</p><pre>$ truffle console</pre><p>in the console type (replace the address with your address)</p><pre>$ SimpleContract.at(&#39;0x4f5c2b6471915398132b627fad0f3089ea5ddd05&#39;);</pre><p>It will return the complete abstraction of our contract. We can get the ABIof the contract by typing the following command:</p><pre>$ SimpleContract.at(&#39;0x4f5c2b6471915398132b627fad0f3089ea5ddd05&#39;).abi;</pre><p>Similarly, we can call the functions of our contract:</p><pre>$ SimpleContract.at(&#39;0x4f5c2b6471915398132b627fad0f3089ea5ddd05&#39;).getName();</pre><p>now, first run the changeName()function and then run getName() function to see if the name is changed to the new name or not.</p><pre>$ SimpleContract.at(&#39;0x4f5c2b6471915398132b627fad0f3089ea5ddd05&#39;).changeName(&#39;your name&#39;);<br>$ SimpleContract.at(&#39;0x4f5c2b6471915398132b627fad0f3089ea5ddd05&#39;).getName();</pre><p>When you are done playing with your smart contract, type $ .exit to close the console mode.</p><h3>4. Writing Tests</h3><p>In general, smart contract test can be written both in Solidity and JavaScript. In this tutorial, We will continue with JavaScript using <a href="https://javascript.info/async-await">async/await</a> notation.</p><p>If we look at our contact again, we want to test:</p><ol><li>the constructor is successfully executed while creating the contract. This can be checked if our getterfunction returns the same value as passed in the constructor.</li><li>the changeName method is successfully changing the value of the namevariable.</li></ol><p>Under the hood, Truffle uses <a href="https://mochajs.org/">Mocha </a>testing framework and <a href="https://www.chaijs.com/">Chai </a>assertion library to test the smart contracts. Furthermore, truffle test command will run the tests from all the test files inside the testfolder.</p><p>But even before writing the tests in JavaScript, let’s write a test to test the constructor in plain English for our getter method:</p><blockquote><em>“This method should return the name ‘my name’.”</em></blockquote><p>You might have noticed that in order to test a method from a particular contract, we need to refer to that contract first. We will do that in our actual test by requiring the artifacts created earlier. Let’s create our test file by typing:</p><pre>$ truffle create test SimpleContract</pre><p>Open the newly created simple_contract.js file from the test folder and we will find a basic test sample there. We can see that Truffle is using contract() instead of describe() as its main function. The contract() provides a list of account available by the Ethereum client (in our case Ganache) which can be used to write tests. Furthermore, it also groups together all the tests for a specific contract. Let’s test the available accounts. Change the contents of your test file as below and run the following command:</p><pre>$ truffle test</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de49f76e2659c53dc01de590c0bd6fe/href">https://medium.com/media/8de49f76e2659c53dc01de590c0bd6fe/href</a></iframe><ul><li>In line 1, we are using artifacts.require() method to request a usable contract abstraction for a specific Solidity contract.</li><li>In line 3, contract() method is used for grouping the tests. It uses a message in order to understand the purpose of the test.</li><li>In line 4, it() is a Mocha notation for a test case.</li></ul><p>The actual test starts in line 4, what we are going to test. As a result, we will see a list of available accounts.</p><h4>Testing Constructor</h4><p>Now let’s write the actual test for the constructor:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c011b0f882c4f1f1e3e644de89b8fbfa/href">https://medium.com/media/c011b0f882c4f1f1e3e644de89b8fbfa/href</a></iframe><ul><li>In line 6, we have created the instance of our contract to access its methods.</li><li>In line 7, we are storing the return value of getName() method so that we can check it out.</li><li>In line 9, we are asserting that the value should be equal to ‘<em>my name</em>’.</li></ul><p>Now run the $ truffle test command and we will see one test is passing!</p><p>Next, we will add another test for our changeName() method. Add the following test at line 11 below test 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e131215d355fba28935ede5f20501a1e/href">https://medium.com/media/e131215d355fba28935ede5f20501a1e/href</a></iframe><p>In this test we are calling the changeName() method with ‘<em>your name</em>’ and in the next line, we are storing this value into a variable. Again run the $ truffle test command.</p><h4>Testing Modifiers</h4><p>The use of function modifiers in the Solidity is also a common pattern to have a better control over contract’s methods execution.</p><p>Let’s add a modifier onlyOwner() that will restrict the execution of a certain method only to the owner of the contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb3761d06ac7aaaa895d4315317965c2/href">https://medium.com/media/bb3761d06ac7aaaa895d4315317965c2/href</a></iframe><p>We have created a private variable owner and assign it to the creator of the contract using the constructor function.</p><ul><li>In line 12, we have declared a function modifier which will check if the caller of the method is the owner of the contract, then continue ( _; ).</li><li>In line 22, the function modifier is assigned to the method changeName() by adding the name of the modifier.</li></ul><p>Open the simple_contract.js file again and add the following test for the modifier. But before doing that, we will re-arrange the test to make our lives even easier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4f7addb850789fb39049ad136cd8cdf/href">https://medium.com/media/f4f7addb850789fb39049ad136cd8cdf/href</a></iframe><p>Instead of creating the contract instance for every test, we have created a global instance of the contract using the beforeEach hook provided by Mocha.</p><p>As we have put the modifier for changeName() method, now only the owner should be able to change the name. This test is specified at line 23. If we run the $ truffle test command again, we see that the test is passed. This is because if we don’t specify the account, ganache automatically uses the first account. In this case, the owner of the contract and caller of the method are the same, so why the test is passed. In order to really check the modifier, let’s use the transaction object in our test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f3088541752eee56deb2f7d463ebec1/href">https://medium.com/media/6f3088541752eee56deb2f7d463ebec1/href</a></iframe><p>Use any other account other than the first account ( accounts[0]) from the list of available accounts and run the test again. You will see your test is failed now because the only owner can call this method. Although, using any other account other than the owner will lead to failing the test but we want our test to pass. This is important, because although the test is asserting a failing behavior, a test itself should always pass its assertion. Here comes the idea of revert into play. The truffle-assertions library has the ability to assert that a transaction reverts as expected. The truffle-assertions package adds additional assertions that can be used to revert transactions in the smart contracts.</p><p>Install the package by running the following command in the terminal:</p><pre>$ npm install truffle-assertions</pre><p>Also import this package at the top or our test file, just below the liner requiring artifacts of the contract:</p><pre>const truffleAssert = require(&#39;truffle-assertions&#39;);</pre><p>add the following test and run the truffle test command again. At this time our test is passed with the expected behavior of the contract!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72610ea161c8ca012b195d42a00fa6fb/href">https://medium.com/media/72610ea161c8ca012b195d42a00fa6fb/href</a></iframe><h4>Listening Events</h4><p>Using the truffle-assertions package that we just installed, we can:</p><ol><li>check the event type</li><li>check events parameters</li><li>print the event</li></ol><p>Let’s add a name event that will be fired every time name is changed.</p><pre>event NameEvent(string evPram);</pre><p>now emit this event in the changeName() function as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a97fb91ad9a0147a518ef3de3b82c3/href">https://medium.com/media/a5a97fb91ad9a0147a518ef3de3b82c3/href</a></iframe><p>add the following test to check if a specific event is present in the transaction or not and run the truffle test command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/980b9f778a52687fcc3e02c782a4792e/href">https://medium.com/media/980b9f778a52687fcc3e02c782a4792e/href</a></iframe><p>We are saving the transaction into a result variable and then check that if ‘NameEvent’ is emitted by the transaction or not.</p><p>Now we will check if the event is emitted with correct parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38ec5be5d6e0af3951668e8ad5b58590/href">https://medium.com/media/38ec5be5d6e0af3951668e8ad5b58590/href</a></iframe><p>In the end, we are going to print out the event parameters and their values emitted by a particular event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff44bce63447ace4163a1d905014b0e8/href">https://medium.com/media/ff44bce63447ace4163a1d905014b0e8/href</a></iframe><p>after running the truffle test command, you will see the transaction emitting the event, name of the emitted event, its parameter, and values.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FfxsqOYnIMEefC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FfxsqOYnIMEefC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FfxsqOYnIMEefC%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="196" frameborder="0" scrolling="no"><a href="https://medium.com/media/28046a9ff8a4b8dbe50a190f4d58ded3/href">https://medium.com/media/28046a9ff8a4b8dbe50a190f4d58ded3/href</a></iframe><p>The source code can be found here in this <a href="https://github.com/m-yahya/truffle-demo">GitHub repo</a>.</p><h3>Related articles</h3><p><a href="https://truffleframework.com/">Truffle</a><br><a href="https://www.npmjs.com/package/truffle-assertions">Truffle Assertions</a><br><a href="https://mochajs.org/">Mocha</a><br><a href="https://www.chaijs.com/">Chai</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4beaa2bd194" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oli-systems/test-driven-solidity-with-truffle-e4beaa2bd194">Test Driven Solidity with Truffle</a> was originally published in <a href="https://medium.com/oli-systems">OLI Systems</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>