<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Elena Gesheva on Medium]]></title>
        <description><![CDATA[Stories by Elena Gesheva on Medium]]></description>
        <link>https://medium.com/@elena_gesheva?source=rss-899aa52b377e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q7rx9sURcG9daAzn_UUJ4Q.png</url>
            <title>Stories by Elena Gesheva on Medium</title>
            <link>https://medium.com/@elena_gesheva?source=rss-899aa52b377e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 01:19:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elena_gesheva/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Retrospective of 25 years life at work]]></title>
            <link>https://medium.com/@elena_gesheva/retrospective-of-25-years-life-at-work-740fd813e5ad?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/740fd813e5ad</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[meritocracy]]></category>
            <category><![CDATA[employment]]></category>
            <category><![CDATA[permanent-employment]]></category>
            <category><![CDATA[contracting]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Mon, 03 Oct 2022 09:05:31 GMT</pubDate>
            <atom:updated>2022-10-03T09:05:31.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeKeDF73juQNomJmVO6nGg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@clemensvanlay?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Clemens van Lay</a> on <a href="https://unsplash.com/s/photos/career?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>How</em> you work is just as important as <em>what</em> you work on. In this first article in over a year of blog silence and introspection I will focus on the “how”. This comeback blog post is my first (and probably last) non-technical publication that concerns the work methodology I have been practicing for the past six months and will hopefully help others make informed choices about their ways of working.</p><p>The hows of this article will focus on the employer-worker arrangements, rather than advice on daily work practices e.g. improving productivity, remote working etc as there is already plenty of good readings on those topics.</p><p>To understand where I am now I had to look back over the past 25 years of my career. Details of each job are in <a href="https://www.linkedin.com/in/elenagesheva/">LinkedIn</a> but below is a short run down of work arrangement types I’ve been through:</p><p><strong>Microsoft ecosystem</strong></p><ul><li>2 years as a student helping manage the university network</li><li>11 years as a permanent employee</li><li>2 years contracting</li><li>2 years as a permanent employee</li></ul><p>2 years break travelling around the world. Left the UK. Moved to Bulgaria.</p><p><strong>Ethereum Ecosystem</strong></p><ul><li>6 years as a permanent employee</li><li>6 months contracting</li></ul><p>The seismic shift in my career was moving from Microsoft to the Ethereum ecosystem accompanied by smaller shifts from permanent to contract employment. Both of these transitions were gradually moving me away from the corporate hierarchies of multinationals and towards the decentralised workspace where the technologies, location, teams were less rigidly defined.</p><p>And since the overall direction was the same, the motivation over the years driving me there had been the same too and is broadly based on two pillars: Fairness and Fulfilment.</p><p><strong>Fulfilment</strong></p><p>I understand fulfilment is not a permanent state in any given job. Sometimes I would work on a project that really makes me jump out of bed in the mornings and other times I’d have to just be cracking on with the necessary. I have no problems maintaining the balance between the exciting and the required. For me that’s leading a balanced and fulfilled work life.</p><p>Additionally what constitutes fulfilment for me isn’t new or revolutionary either, and <a href="https://www.danpink.com/books/drive/">Daniel Pink had described it well in his bestselling book “Drive”</a></p><blockquote>it is the deep human need to direct our own lives, to learn and create new things, and to do better by ourselves and our world.</blockquote><p>He calls these fulfilment composites “autonomy, mastery and purpose” and they form the basis of how I had naturally directed my work life through the years.</p><p>The most autonomy I have experienced at work so far is surprisingly in a permanent job at a 6000-employee large consultancy in the UK where I had the freedom to select the projects I worked on and team members to work with. Additionally I received some of the best training available in the field that was a mix of technical and people-skill courses I regularly took while climbing the corporate ladder. To this day it is still the longest job I’ve had of 4 years having delivered altogether 6 large projects each with a different team of between 3 to 7 people. In essence this job resembled an open skilled job market more than the conventional permanent employment.</p><p>On another hand in open source software and specifically Ethereum, despite its decentralisation properties at the core, projects are very centralised and rigid. Open developer markets still do not exist fully and most developers I know are simply permanently employed at a single company. This has often led autonomy, mastery and purpose to all suffer since there is little wiggle room to switch work to external repositories or teams and thereon the ability to improve skills and find meaning when fenced in a single company GitHub portfolio decreases as well.</p><p>To make matters worse in open source software, unlike closed source software, it is essential that developers are free to contribute to different products and initiatives. This is either because they’ve hit a blocker in a library they need to solve or they’ve come across something interesting that’s worth exploring further. At other times I’ve personally felt the need to go off and do something different for a while, evolve a personal idea or contribute to someone else’s interesting idea. Respectively, on certain projects I have sometimes preferred to involve a specific external contributor in the work which has more often than not failed because they would also normally be occupied in a permanent position elsewhere.</p><p>To make such cross project collaborations even more complicated, permanent employer contracts often lack non-exclusivity clauses that ultimately prevent you from being able to contribute externally without your employer’s consent. And even if a company didn’t forbid you legally, it is still expected that you would only contribute to external projects only part-time.</p><p>Ultimately, the best person for a job is not always someone on the company’s employee list. A developer can feel passionate about and contribute to multiple projects to learn, improve and find purpose. This should be okay if it keeps them fulfilled and as long as it is fair, which brings me onto my next point.</p><h4>Fairness</h4><p>What I give as time, skills and effort has to be paid back in money and benefits that were exactly equal. Nothing more, nothing less.</p><p>What we normally get back for our work is money, however let me first go over the popular benefits options I have been offered over the years of permanent employment and I’ll explain why they don’t attract me personally:</p><ul><li><em>unlimited holidays</em> — there is usually one condition that comes with this benefit and it is “as long as your job is done you can take as much time off as you want”. However having your work “done” is subjective and normally depends on how much time off the rest of the company takes relative to you. I had ended up taking less time-off than I actually needed as a result. Ultimately the most holidays I’ve ever taken was at a company that had fixed 23 paid days off where I ended up taking that plus another 20 unpaid days off I spent at the beach not feeling an ounce of guilt.</li><li><em>company shares and token options</em> — looks appealing at first, however exercising shares is not always as straight forward as it sounds and you need to normally wait a year to find out the actual process for yourself. The last company I worked for still hasn’t issued my shares 6 months after I requested to exercise. With tokens it’s a similar situation and I‘ve always had to wait months, even years for company tokens to be issued and even then these have normally been subject to vesting and/or locking that restrict your access for a further number of years. Overall I treat it as a very long term, unsafe option for a minimal salary substitution at best.</li><li><em>laptop, co-working space </em>— I already own my tech and have a working setup that far exceeds anything a company and co-working space will be able to provide me. The social aspect of co-working I normally catch up on in conferences and events or team get togethers when we need to knock something out more effectively in person.</li><li><em>health insurance, fitness fees</em> —Private health insurance is normally offered for US-based employees only which I am not. Even if that were provided for me it actually makes it more difficult to get access to quality private healthcare specifically where I am. As for the wellness fees, I keep fit at places that are not the gym (the forest is at my doorstep, open 24/7 and free).</li></ul><p>Finally on the subject of money, the only advantage for me over the years for having a permanent salary has been predictability. The fact that it hits your account on a given date, likely once or twice per month. The reassurance that my balance will go up is what attracted me when I had a mortgage and other loans.</p><p>Contracting salaries on another hand are higher but hold more uncertainty and additionally don’t cover holidays and sick days. Thinking back on the two instances in these 25 years that I have been very ill in both cases it has been caused by the stress of the last permanent job at the time (having had it build up over the years). In the first case it was as bad as to cause the breakup of my long-term relationship. In both cases transitioning to contracting made me happier, healthier and more satisfied overall while I still earned the same as I was working less but paid more.</p><p>Another argument for getting paid on an hourly basis is that I could rarely do focussed work for 40 hours a week every week consistently and even though most companies won’t sanction you for taking a few hours to run some errands or walk the dog, I have personally felt it’s unfair on the company and prefer to be paid for the exact hours I put in. The opposite is valid too, for the busy periods during a release or an incident handling I would also want to be paid for the extra time I spent on evenings and weekends.</p><p>For the past six months I have been working in a setup where I simply get paid a decent hourly rate for the exact hours I put in. I’ve come to the conclusion this is the setup that best allows me to have a fair and fulfilled work engagements on products, protocols and platforms I feel passionate about building.</p><h4>Future of work</h4><p>Ultimately what worked best at a 6000-employee consultancy, albeit closed sourced, is that it organised clients, projects and teams around its workforce and core competencies, allowing its employees to focus on choosing and running the projects in teams that were best for the job, while in parallel helping them master their skillset. It was sizeable enough to resemble an open-project market where its consultants were more akin to well cared for freelancers than permanent employees.</p><p>As dire as Ethereum employment arrangements are today we are uniquely positioned to propel employment into its next evolutionary step to enable the scarce human resources to a) be super motivated by making best use of their skills and interests and b) solve developer resourcing crisis.</p><p>What got me into Ethereum in the first place was a post on the <a href="https://blog.colony.io/the-future-of-work-cf99211e7ac4/">“Future of work”</a> which resonated deeply with my core values system. The decentralisation properties Ethereum stood on formed the perfect foundation for building a fair and fulfilled workplace. I was hooked and spent the next 3 years building the <a href="https://github.com/JoinColony/colonyNetwork/releases/tag/glider">first release of the protocol</a> that underpinned that idea. <br>I am of the opinion that until a meritocratic work form normalises, contracting is the next best option for developers who want to be free to live how they want and work on what they want while being rewarded fairly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=740fd813e5ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity 0.6.x Features: Inheritance]]></title>
            <link>https://medium.com/better-programming/solidity-0-6-x-features-inheritance-5d760dc1ad22?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d760dc1ad22</guid>
            <category><![CDATA[c3]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[solidity-language]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 10:32:33 GMT</pubDate>
            <atom:updated>2020-07-01T13:29:00.990Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about inheritance in Solidity and how you can use it to build smart contracts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8H51GOpSIc-aW1kcGiA7A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@contrastband?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Craig Sybert</a> on <a href="https://medium.com/s/photos/twins?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Similar to object-oriented programming in Solidity — a contract-oriented language — the inheritance and polymorphism features are as widely adopted and critical for the language evolution. There are hardly any Solidity developers who haven’t used these language features in their contracts to decouple logic and increase code reuse. With version 0.6 of the language, the main improvements introduced are to make existing rules explicit in addition to introducing interface inheritance and disallowing the dangerous state variable shadowing. The compiler continues to use C3 Linearization — see <a href="https://solidity.readthedocs.io/en/latest/contracts.html#inheritance">Solidity documentation</a> for inheritance.</p><h3>Explicit Virtual and Override</h3><p>Functions are no longer virtual by default. This means that a call to a non-virtual function will always execute that function regardless of any other contract in the inheritance hierarchy. This reduces ambiguity that exists in version 0.5, where all functions are implicitly virtual, allowing them to be overridden further down the inheritance structure. This is especially dangerous in big inheritance graphs where this ambiguity can lead to unintended behaviour and bugs.</p><p>For example, in contract C below, calling setValue calls the most derived implementation which is from contract B. However, this is non-obvious from the implementation.</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.5.17;<br><strong>contract</strong> A {<br>    <strong>uint</strong> <strong>public</strong> x;<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>public</strong> {<br>        x <strong>=</strong> _x;<br>    }<br>}<br><br><strong>contract</strong> B {<br>    <strong>uint</strong> <strong>public</strong> y;<br>    <strong>function</strong> setValue(<strong>uint</strong> _y) <strong>public</strong> {<br>        y <strong>=</strong> _y;<br>    }<br>}<br><br><strong>contract</strong> C <strong>is</strong> A, B {<br>}</pre><p>With version 0.6 for the example above, the compiler raises a type error: Derived contract must override function &quot;setValue&quot;. Two or more base classes define functions with the same name and parameter types. The above is an example of multiple inheritances where the same function is inherited from multiple base classes: A and B. In this case, it has to be overridden and the bases have to be listed in the override specifier. It’s important to note that the order in override(A,B) does not matter — specifically, it does not change the behaviour of super. This is still dictated by the C3 linearization of the inheritance graph which is determined by the order in the contract C is A, B { ... } declaration.</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.6.10;<br><strong>contract</strong> A {<br>    <strong>uint</strong> <strong>public</strong> x;<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>public</strong> <strong>virtual</strong> {<br>        x <strong>=</strong> _x;<br>    }<br>}<br><br><strong>contract</strong> B {<br>    <strong>uint</strong> <strong>public</strong> y;<br>    <strong>function</strong> setValue(<strong>uint</strong> _y) <strong>public</strong> <strong>virtual</strong> {<br>        y <strong>=</strong> _y;<br>    }<br>}<br><br><strong>contract</strong> C <strong>is</strong> A, B {<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>public</strong> <strong>override</strong>(A,B) {<br>        A.setValue(_x);<br>    }<br>}</pre><p>Note that you can only override functions if they are marked virtual. Additionally, any overriding function must be marked override. If that again should be overridable, it has to also be marked virtual.</p><p>interface functions are implicitly virtual so when implementing an interface you have to explicitly override its functions in the implementation. There is an ongoing discussion on this design <a href="https://github.com/ethereum/solidity/issues/8281">here</a>.</p><p>It’s worth noting that the keyword super works as it did before. It calls the function one level higher up in the flattened inheritance hierarchy. Also unchanged: super is still not allowed on external functions.</p><h3>Interfaces Can Inherit</h3><p>This functionality is new to version 0.6 and allows interface inheritance. The resulting interface is a combination of all inherited interfaces’ functions which the contract has to implement.</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.6.10;<br><strong>interface</strong> X {<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>external</strong>;<br>}<br><br><strong>interface</strong> Y <strong>is</strong> X {<br>    <strong>function</strong> getValue() <strong>external</strong> <strong>returns</strong> (<strong>uint</strong>);<br>}<br><br><strong>contract</strong> Z <strong>is</strong> Y {<br>    <strong>uint</strong> x;<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>external</strong> <strong>override</strong> { x <strong>=</strong> _x; }<br>    <strong>function</strong> getValue() <strong>external</strong> <strong>override</strong> <strong>returns</strong> (<strong>uint</strong>) { <strong>return</strong> x; }<br>}</pre><p>Note that if the contract does not implement all functions, it has to be marked as abstract.</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.6.10;<br><strong>abstract</strong> <strong>contract</strong> Z <strong>is</strong> Y {<br>    <strong>uint</strong> x;<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>external</strong> <strong>override</strong> { x <strong>=</strong> _x; }<br>}</pre><h3>Abstract Contracts</h3><p>With version 0.5, a contract that doesn’t implement all of its functions is implicitly made abstract by the compiler:</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.5.17;<br><strong>contract</strong> X {<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>public</strong> <strong>virtual</strong>;<br>}</pre><p>With 0.6, this differentiation has to be explicit with the compiler generating error contract X should be made abstract. Otherwise:</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.6.10;<br><strong>abstract</strong> <strong>contract</strong> X {<br>    <strong>function</strong> setValue(<strong>uint</strong> _x) <strong>public</strong> <strong>virtual</strong>;<br>}</pre><h3>Public Variables Safer Override for External Functions</h3><p>Although this feature existed before 0.6, it is now safer with the added checks that the getter function of the variable (generated by the compiler) matches the parameter and return type of the overridden external function. With version 0.5, it is possible that these were allowed to differ, as shown in the following example:</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.5.17;<br><strong>interface</strong> A<br>{<br>    <strong>function</strong> f() <strong>external</strong> <strong>pure</strong> <strong>returns</strong>(<strong>uint8</strong>);<br>}<br><br><strong>contract</strong> B <strong>is</strong> A<br>{<br>    <strong>uint256</strong> <strong>public</strong> f <strong>=</strong> 257;<br>}</pre><p>Contract A&#39;s call to underlying contract B would return 1 as the 257 value overflows when cast to uint8.</p><p>With 0.6, now the above generates TypeError: Overriding public state variable return types differ, forcing us to resolve the type conflict and avoiding the overflow:</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.6.10;<br><strong>interface</strong> A<br>{<br>    <strong>function</strong> f() <strong>external</strong> <strong>pure</strong> <strong>returns</strong>(<strong>uint256</strong>);<br>}<br><br><strong>contract</strong> B <strong>is</strong> A<br>{<br>    <strong>uint256</strong> <strong>public</strong> <strong>override</strong> f <strong>=</strong> 257;<br>}</pre><p>Note that public state variables can only override external functions and it remains disallowed for variables to override internal or public functions.</p><h3>No State Variables Shadowing</h3><p>Inheriting visible state variables with the same name in version 0.5 was allowed by the compiler and is only raised as a problem by some static analysis tools. The following example demonstrates the problem with this design:</p><pre><strong>pragma</strong> solidity <strong>^</strong>0.5.17;<br><strong>contract</strong> A {<br>    <strong>uint</strong> <strong>public</strong> x;<br><br>    <strong>function</strong> setValue1(<strong>uint</strong> _x) <strong>public</strong> { x <strong>=</strong> _x; }<br>}<br><br><strong>contract</strong> B <strong>is</strong> A {<br>    <strong>uint</strong> <strong>public</strong> x;<br><br>    <strong>function</strong> setValue2(<strong>uint</strong> _x) <strong>public</strong> { x <strong>=</strong> _x; }<br>}</pre><p>In this context, functions in contract A referencing x are using its own instance of that state variable - A.x. For B, it&#39;s B.x. Therefore the result of calling B.setValue2(100) would be that B.x will be set to 100 while calling B.setValue1(200) will set A.x to 200.</p><p>With 0.6, this is now prohibited and raises a compiler DeclarationError: Identifier already declared error.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d760dc1ad22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solidity-0-6-x-features-inheritance-5d760dc1ad22">Solidity 0.6.x Features: Inheritance</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity 0.6.x Features: Fallback and Receive Functions]]></title>
            <link>https://medium.com/better-programming/solidity-0-6-x-features-fallback-and-receive-functions-69895e3ffe?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/69895e3ffe</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 09:00:13 GMT</pubDate>
            <atom:updated>2020-06-22T19:33:59.523Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring two key features of Solidity 0.6.x</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kvW32ZBLNhwokey4Nbk8w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bdchu614?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brendan Church</a> on <a href="https://unsplash.com/s/photos/cross-road?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>In versions of Solidity before 0.6.x, developers typically used the <a href="https://solidity.readthedocs.io/en/v0.5.15/contracts.html#fallback-function">fallback function</a> to handle logic in two scenarios:</p><ul><li>A contract received ether and no data.</li><li>A contract received data, but no function matched the function called.</li></ul><p>The main use case of the pre-0.6.x fallback function was to receive Ether and react to it — a typical pattern used by token-style contracts to reject transfers, emit events, or forward the Ether. The function executes when a contract is called without any data (e.g. via .send() or .transfer() functions). The 0.5.x syntax is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f65fc7a5c21f25fa19fb9154e32e2c4/href">https://medium.com/media/9f65fc7a5c21f25fa19fb9154e32e2c4/href</a></iframe><p>The second use case was made popular by the “delegate proxy” pattern for implementing upgradeable contracts. It has a simple proxy contract that only declares a fallback function. The fallback function is invoked when no function in the contract matches the function identifier in the call data. This permits the “delegate proxy” pattern where functionality is implemented outside the called contract. Here is an example of the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c961fd3baea78a34097d49658a1f3630/href">https://medium.com/media/c961fd3baea78a34097d49658a1f3630/href</a></iframe><p>Calling the contract uses assembly code that we won’t go into here, but you can read more in <a href="https://docs.openzeppelin.com/upgrades/2.6/proxies">Zeppelin’s documentation</a>.</p><h3>Splitting the Fallback Function</h3><p>We realised that the dual purpose of the function confused developers, which could lead to potential security problems. For example, a developer typically implements a fallback function expecting only Ether transfers to call it, but it is also called when a function is missing from a contract. And confusingly, as this was expected behaviour, no error was reported. Here is an example of this confusing behaviour:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a663ea9a42a22e099b76ffa5577845f4/href">https://medium.com/media/a663ea9a42a22e099b76ffa5577845f4/href</a></iframe><p>When calling CharitySplitter.donate() with a charity contract address, its processDonation function is correctly invoked to process the donation as expected. However, if by mistake the Receiver contract address is passed, its fallback function ends up being called, swallowing the sent value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d296bd380344b4183e7eca8efe1bfe6b/href">https://medium.com/media/d296bd380344b4183e7eca8efe1bfe6b/href</a></iframe><p>Since the EVM is untyped, Solidity is unable to check the actual type of a contract from its address and has to rely on what the user supplies. The function signatures also do not provide a perfect solution against type confusion but can work in many cases.</p><p>This is why the fallback function in version 0.6x was split into two separate functions:</p><ul><li><a href="https://solidity.readthedocs.io/en/latest/contracts.html#receive-ether-function">receive()</a> external payable — For empty call data (and any value)</li><li><a href="https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function">fallback()</a> external payable — When no other function matches (not even the receive function). Optionally payable.</li></ul><p>This separation provides an alternative to the fallback function for contracts that want to receive plain Ether.</p><h3>receive()</h3><p>A contract can now have only one receive function that is declared with the syntax receive() external payable {…} (without the function keyword).</p><p>It executes on calls to the contract with no data (calldata), such as calls made via send() or transfer().</p><p>The function cannot have arguments, cannot return anything, and must have external visibility and payable state mutability. To replicate the example above under 0.6.0, use the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82c1c64d709bcdb429de9599437959cc/href">https://medium.com/media/82c1c64d709bcdb429de9599437959cc/href</a></iframe><h3>fallback()</h3><p>The fallback function now has a different syntax that is declared using fallback() external [payable] {…} (without the function keyword). This function cannot have arguments, cannot return anything, and must have external visibility. The fallback function always receives data, but to also receive Ether, you should mark it as payable. To replicate the example above under 0.6.0, use the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4597f1d932ad380ac3e6aee1e2a5802b/href">https://medium.com/media/4597f1d932ad380ac3e6aee1e2a5802b/href</a></iframe><h3>Migrated and Fixed Sample Contract</h3><p>Thus, we translate the problematic contract to v0.6.x , having it declare a receive() function that only accepts incoming Ether without data and avoids the type confusion that led to the loss of value demonstrated above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef25e9f5bc3327230fbd373c1e849b80/href">https://medium.com/media/ef25e9f5bc3327230fbd373c1e849b80/href</a></iframe><p>The calls to the fixed contract will now revert when calls with the Receiver contract address fail:</p><pre>// The following call now reverts<br>await charitySplitter.donate(badCharity, { value: 10 });</pre><p>We hope you find the logical division of the fallback function clearer for your design and welcome any feedback you have on the new syntax.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69895e3ffe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solidity-0-6-x-features-fallback-and-receive-functions-69895e3ffe">Solidity 0.6.x Features: Fallback and Receive Functions</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity 0.6.x Features: The Try/Catch Statement]]></title>
            <link>https://medium.com/better-programming/solidity-0-6-x-features-try-catch-statement-8c4c1bb73309?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4c1bb73309</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 08:53:59 GMT</pubDate>
            <atom:updated>2020-04-22T03:14:30.133Z</atom:updated>
            <content:encoded><![CDATA[<h4>Originally published on the <a href="https://solidity.ethereum.org/2020/01/29/solidity-0.6-try-catch/">Solidity Ethereum Foundation Blog</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kewaJNAYCJSAfVMLsf-63A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wilsonjim?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jim Wilson</a> on <a href="https://unsplash.com/s/photos/require?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The <a href="https://solidity.readthedocs.io/en/latest/control-structures.html#try-catch">try/catch syntax introduced in 0.6.0</a> is arguably the biggest leap in error handling capabilities in Solidity since reason strings for revert and require were released in v0.4.22. Both try and catch have been reserved keywords <a href="https://solidity.readthedocs.io/en/v0.5.9/miscellaneous.html#reserved-keywords">since v0.5.9</a>, and now we can use them to handle failures in external function calls without rolling back the complete transaction (state changes in the called function are still rolled back, but the ones in the calling function aren’t).</p><p>We’re moving one step away from the purist all-or-nothing approach in a transaction lifecycle, which falls short of the practical behaviour we often want.</p><h3>Handling External Call Failures</h3><p>The try/catch statement allows you to react on failed <em>external</em> calls and <em>contract creation</em> calls, so you cannot use it for <em>internal</em> function calls. Note that to wrap a public function call within the same contract with try/catch, it can be made external by calling the function with this.</p><p>The example below demonstrates how try/catch is used in a factory pattern where contract creation might fail. The following CharitySplitter contract requires a mandatory address property, _owner, in its constructor.</p><pre>pragma solidity ^0.6.1;</pre><pre>contract CharitySplitter {<br>    address public owner;<br>    constructor (address _owner) public {<br>        require(_owner != address(0), &quot;no-owner-provided&quot;);<br>        owner = _owner;<br>    }<br>}</pre><p>There’s a factory contract — CharitySplitterFactory — which is used to create and manage instances of CharitySplitter. In the factory, we can wrap the new CharitySplitter(charityOwner) in a try/catch as a failsafe for when that constructor might fail because of an empty charityOwner being passed.</p><pre>pragma solidity ^0.6.1;<br>import &quot;./CharitySplitter.sol&quot;;<br>contract CharitySplitterFactory {<br>    mapping (address =&gt; CharitySplitter) public charitySplitters;<br>    uint public errorCount;<br>    event ErrorHandled(string reason);<br>    event ErrorNotHandled(bytes reason);<br>    function createCharitySplitter(address charityOwner) public {<br>        try new CharitySplitter(charityOwner)<br>            returns (CharitySplitter newCharitySplitter) <br>        {<br>            charitySplitters[msg.sender] = newCharitySplitter;<br>        } catch {<br>            errorCount++;<br>        }<br>    }<br>}</pre><p>Note that with try/catch, only exceptions happening inside the external call itself are caught. Errors inside the expression are not caught — for example, if the input parameter for the new CharitySplitter is itself part of an internal call, any errors it raises will not be caught.</p><p>A sample demonstrating this behaviour is the modified createCharitySplitter function. Here, the CharitySplitter constructor input parameter is retrieved dynamically from another function — getCharityOwner. If that function reverts, in this example with &quot;revert-required-for-testing&quot;, that won’t be caught in the try/catch statement.</p><pre>function createCharitySplitter(address _charityOwner) public {<br>    try new CharitySplitter(getCharityOwner(_charityOwner, false))<br>        returns (CharitySplitter newCharitySplitter)<br>    {<br>        charitySplitters[msg.sender] = newCharitySplitter;<br>    } catch (bytes memory reason) {<br>        ...<br>    }<br>}<br>function getCharityOwner(address _charityOwner, bool _toPass)<br>        internal returns (address) {<br>    require(_toPass, &quot;revert-required-for-testing&quot;);<br>    return _charityOwner;<br>}</pre><h3>Retrieving the Error Message</h3><p>We can further extend the try/catch logic in the createCharitySplitter function to retrieve the error message if one was emitted by a failing revert or require and emit it in an event. There are two ways to achieve this:</p><h4>1. Using ‘catch Error(string memory reason)&#39;</h4><pre>function createCharitySplitter(address _charityOwner) public {<br>    try new CharitySplitter(_charityOwner) returns (CharitySplitter newCharitySplitter) <br>    { <br>        charitySplitters[msg.sender] = newCharitySplitter;<br>    }<br>    catch Error(string memory reason) <br>    {<br>        errorCount++;<br>        CharitySplitter newCharitySplitter = new<br>            CharitySplitter(msg.sender);<br>        charitySplitters[msg.sender] = newCharitySplitter;<br>        // Emitting the error in event<br>        emit ErrorHandled(reason);<br>    }<br>    catch <br>    {<br>        errorCount++;<br>    }<br>}</pre><p>This emits the following event on a failed constructor require error:</p><pre>CharitySplitterFactory.ErrorHandled(<br>    reason: &#39;no-owner-provided&#39; (type: string)<br>)</pre><h4>2. Using ‘catch (bytes memory reason)&#39;</h4><pre>function createCharitySplitter(address charityOwner) public {<br>    try new CharitySplitter(charityOwner)<br>        returns (CharitySplitter newCharitySplitter) <br>    {<br>        charitySplitters[msg.sender] = newCharitySplitter;<br>    } <br>    catch (bytes memory reason) {<br>        errorCount++;<br>        emit ErrorNotHandled(reason);<br>    }<br>}</pre><p>This emits the following event on a failed constructor require error:</p><pre>CharitySplitterFactory.ErrorNotHandled(<br>  reason: hex&#39;08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000116e6f2d6f776e65722d70726f7669646564000000000000000000000000000000&#39; (type: bytes)</pre><p>The above two methods for retrieving the error string produce a similar result. The difference is that the second method doesn’t ABI-decode the error string. The advantage of the second method is it’s also executed if ABI decoding the error string fails or if no reason was provided.</p><h3>Future Plans</h3><p>There are plans to release support for error types, meaning we will be able to declare errors in a similar way to events — allowing us to catch different type of errors, for example:</p><pre>catch CustomErrorA(uint data1) { … }<br>catch CustomErrorB(uint[] memory data2) { … }<br>catch {}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4c1bb73309" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/solidity-0-6-x-features-try-catch-statement-8c4c1bb73309">Solidity 0.6.x Features: The Try/Catch Statement</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parameterized Transaction Reviews]]></title>
            <link>https://medium.com/colony/parameterized-transaction-reviews-11f0cdc40479?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f0cdc40479</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Thu, 20 Sep 2018 12:37:59 GMT</pubDate>
            <atom:updated>2018-09-20T12:37:59.489Z</atom:updated>
            <content:encoded><![CDATA[<h4>For when a multi-sig is just not granular enough for your transaction review needs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YelHtx101hWJUguKVHRdg.png" /><figcaption>It’s like that game “Operation”, but for bytecode!</figcaption></figure><p>Multi-signature transactions are one of the most useful patterns for smart contracts and the dApps that utilize them. But in the ‘vanilla’ implementation of multi-signature design, transaction reviewers (owners), are assigned <em>contract-wide</em> and review <em>all</em> transactions. Colony’s requirements for multi-sig transactions are more complex than this provides. We have multiple user roles within a Colony, and depending on context, <em>which</em> signatures are required for various operations may differ.</p><p>For example, one of the base building blocks in Colony is the Task. A task is a small unit of work to be done for an organization, and it has three distinct roles defined to coordinate that work: a manager, an evaluator and a worker.</p><p>There are many tasks within each colony and each can have a different set of users assigned to these three roles for each task. We want the flexibility to have any combination of two of the three task roles to be configurable as reviewers on a particular task change <em>type </em>as shown in the example set of four Taskchange functions below.</p><pre>+------------------------+-----------------+-----------------+<br>|      Function          | Reviewer Role 1 | Reviewer Role 2 |<br>+------------------------+-----------------+-----------------+<br>| setTaskBrief           | manager         | worker          |<br>| setTaskDueDate         | manager         | worker          |<br>| setTaskEvaluatorPayout | manager         | evaluator       |<br>| setTaskWorkerPayout    | manager         | worker          |<br>+------------------------+-----------------+-----------------+</pre><p>If a task manager decides to change some of its properties, such as to change the work brief (specification) hash, this change should also be reviewed by the worker, who will have to adjust to the new terms in order to claim a payout and reputation gain. In another case, if a manager wants to change the evaluator’s payout, the change should be approved by the evaluator rather than the worker.</p><p>Additionally we don’t want to have each role sign and submit a transaction to the blockchain individually — this will cost too much gas to be manageable in the long term. The change should instead be agreed upon in advance, and then committed to the blockchain only once with the required signatures.</p><p>To achieve all this, we created the <em>parameterized transaction review </em>design pattern, and implemented it within Colony tasks.</p><p>Our implementation builds upon the ideas in<a href="https://github.com/christianlundkvist/simple-multisig">simple-multisigdesign by Christian Lundkvist</a>, where transaction data is submitted and only executed once (on chain) after all required signatures are received (off chain).</p><p>Let’s get into the details of how this all works!</p><h4>Constructing the task change transaction data</h4><p>We’ll refer to a simplified version of the Colony Task data structure and a set of update functions to demonstrate the design.</p><pre>struct Task {<br>    bytes32 specificationHash;<br>    uint256 dueDate;<br>    // Role Ids mapping to user addresses, using role Ids:<br>    // 0 - task manager, 1 - task evaluator, 2 - task worker<br>    mapping (uint8 =&gt; address) roles;<br>    // Maps task role ids (0,1,2) to payment amount<br>    mapping (uint8 =&gt; uint256) payouts;<br>}<br>  <br>mapping (uint256 =&gt; Task) tasks;<br>uint256 taskCount;</pre><pre>uint8 constant MANAGER = 0;<br>uint8 constant EVALUATOR = 1;<br>uint8 constant WORKER = 2;</pre><pre>function setTaskBrief(uint256 _id, bytes32 _specificationHash) public {<br>    tasks[_id].specificationHash = _specificationHash;<br>}<br>  <br>function setTaskDueDate(uint256 _id, uint256 _dueDate) public {<br>    tasks[_id].dueDate = _dueDate;<br>}<br>  <br>function setTaskEvaluatorPayout(uint256 _id, uint256 _amount) public {<br>    tasks[_id].payouts[EVALUATOR] = _amount;<br>}<br>  <br>function setTaskWorkerPayout(uint256 _id, uint256 _amount) public {<br>    tasks[_id].payouts[WORKER] = _amount;<br>}</pre><p>The four functions above have to check two different pairs of signatures as specified in requirements table above.</p><p>Additionally, there are many tasks within a colony, and each task will have its own set of users assigned to roles — so the required signatures should be dynamically retrieved from the task being updated.</p><p>As I mentioned, gas is expensive. We don’t want users to be constantly sending transactions to the blockchain if they don’t have to. So in this case, the manager creates a transaction <em>locally</em> for the operation that needs to be performed:</p><pre>setTaskBrief(1, &quot;0x017dfd85d4f6cb4dcd715a88101f7b1f06cd1e009b2327a0809d01eb9c91f232&quot;)</pre><p>which is composed into the following transaction data bytes:</p><pre>0xda4db2490000000000000000000000000000000000000000000000000000000000000001017dfd85d4f6cb4dcd715a88101f7b1f06cd1e009b2327a0809d01eb9c91f232</pre><p>This raw byte data is then signed as a message with the Manager’s key, and through the magic of <a href="https://github.com/JoinColony/colonyJS">colonyJS</a>, the signed message can be sent as a JSON object to the Worker, off-chain. The worker may inspect the transaction if necessary to make sure that the raw byte data corresponds to the agreed upon change, and then add their signature to the transaction.</p><p>When both signatures have been collected, the transaction can be submitted to the blockchain, with all parameters passed as arguments to the executeTaskChange function:</p><pre>function executeTaskChange(<br>uint8[] _sigV,<br>bytes32[] _sigR,<br>bytes32[] _sigS, <br>uint8[] _mode,<br>uint256 _value,<br>bytes _data) public stoppable<br>{<br>   // The full function appears later in this post.<br>}</pre><h4>Deconstructing the transaction</h4><p>As the task change is submitted to the blockchain, the executeTaskChange function then needs a way to pull out the byte data that corresponds to which task is being changed, what the change is, and check it against which signatures are authorized to approve the change.</p><p>Our solution pulls the relevant information straight from the embedded byte data, using <a href="https://solidity.readthedocs.io/en/v0.4.24/assembly.html#opcodes">Solidity assembly </a><a href="https://solidity.readthedocs.io/en/v0.4.24/assembly.html#opcodes">mload function</a> to read values from EVM memory which is where the input _data parameter is held. On-chain, the deconstructCall method gets the task Id and the signature of the task change function.</p><pre>function deconstructCall(bytes _data) internal pure returns (bytes4 sig, uint256 taskId) {<br>    assembly {<br>      sig := mload(add(_data, 0x20))<br>      taskId := mload(add(_data, 0x24))<br>    }<br>  }</pre><p>Let’s break all that down a bit more!</p><p>deconstructCall operates on the raw transaction _data bytes. Recall that the manager wants to setTaskBrief on task id 1 with a new work specification. This translates to the following raw transaction:</p><pre>0xda4db2490000000000000000000000000000000000000000000000000000000000000001017dfd85d4f6cb4dcd715a88101f7b1f06cd1e009b2327a0809d01eb9c91f232</pre><p>Using remix, we can inspect the result in EVM memory:</p><pre>0x90: 00000000000000000000000000000044<br>0xa0: da4db249000000000000000000000000<br>0xb0: 00000000000000000000000000000000<br>0xc0: 00000001017dfd85d4f6cb4dcd715a88<br>0xd0: 101f7b1f06cd1e009b2327a0809d01eb<br>0xe0: 9c91f232</pre><p>The transaction data is a dynamic bytes type in Solidity, which is packed tightly in calldata. The first slot (in example above, slot 0x90) represents its length (0x44, or 68 in decimal notation). These 68 bytes comprise 4 bytes for the function signature, 32 bytes for the first function parameter (uint256 taskID), and 32 bytes for the second function parameter (bytes32 specificationHash).</p><p>So we must add 0x20 (or 32 bytes) to find the start of the actual transaction data value, skipping over the length. The first 4 bytes there hold the function signature we want to call on the task:</p><p>sig := mload(add(_data, 0x20)) returns da4db249.</p><p>The taskID is analogous, but it will be located another 32 bytes later in the next memory slot, so we add 0x24:</p><p>taskId := mload(add(_data, 0x24)) returns the taskID.</p><p><em>(Note that here we rely on the </em><em>taskId to be the first parameter of the function call for updating a task.)</em></p><h4>Setting the permissions</h4><p>The last piece of the puzzle is to get the transaction to go through <em>if and only if</em> the signatures of the correct people are present, and to revert in all other cases.</p><p>For specifying the reviewer rules we map function signatures to 2 reviewer roles array, e.g. setTaskBrief =&gt; [0,2]</p><p>For simplicity and security we initialize the task update function reviewers in the constructor:</p><pre>// Mapping function signature to 2 task role reviewers<br>mapping (bytes4 =&gt; uint8[2]) public reviewers;<br>  <br>constructor() <br>{        setFunctionReviewers(bytes4(keccak256(&quot;setTaskBrief(uint256,bytes32)&quot;)), MANAGER, WORKER);<br>    setFunctionReviewers(bytes4(keccak256(&quot;setTaskDueDate(uint256,uint256)&quot;)), MANAGER, WORKER);</pre><pre>setFunctionReviewers(bytes4(keccak256(&quot;setTaskEvaluatorPayout(uint256,uint256)&quot;)), MANAGER, EVALUATOR);      <br>  setFunctionReviewers(bytes4(keccak256(&quot;setTaskWorkerPayout(uint256,uint256)&quot;)), MANAGER, WORKER);<br>}<br>  <br>function setFunctionReviewers(bytes4 _sig, uint8 _firstReviewer, uint8 _secondReviewer)<br>private<br>{<br>  uint8[2] memory _reviewers = [_firstReviewer, _secondReviewer];<br>  reviewers[_sig] = _reviewers;<br>}</pre><h4><strong>Putting it together to execute a signed and reviewed task update</strong></h4><p>We reroute the public task update functions to be called only internally and expose a single public executeTaskChange function to call them instead, which checks that the the required signatures match those defined in the reviewer rules before executing the change function call.</p><pre>modifier self() {<br>  require(address(this) == msg.sender);<br>  _;<br>}</pre><pre>function executeTaskChange(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, uint256 _value, bytes _data)<br>public <br>{<br>  require(_sigR.length == 2);<br>  bytes4 sig;<br>  uint256 taskId;<br>  (sig, taskId) = deconstructCall(_data);</pre><pre>bytes32 msgHash = keccak256(abi.encodePacked(address(this),      address(this), _value, _data, taskChangeNonces[taskId]));</pre><pre>address[] memory reviewerAddresses = new address[](2);<br>  for (uint i = 0; i &lt; 2; i++) <br>  {<br>     bytes32 txHash;<br>     txHash = keccak256(abi.encodePacked(&quot;\x19Ethereum Signed Message:\n32&quot;, msgHash));<br>     reviewerAddresses[i] = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]);<br>   }<br>    <br>   require(reviewerAddresses[0] != reviewerAddresses[1]);<br>    <br>   require(<br>      reviewerAddresses[0] == tasks[taskId].roles[reviewers[sig][0]]<br>      ||<br>      reviewerAddresses[0] == tasks[taskId].roles[reviewers[sig][1]]<br>    );<br>  <br>   require(<br>      reviewerAddresses[1] == tasks[taskId].roles[reviewers[sig][0]]    <br>      ||<br>      reviewerAddresses[1] == tasks[taskId].roles[reviewers[sig][1]]<br>    );</pre><pre>taskChangeNonces[taskId] += 1;<br>   require(executeCall(address(this), _value, _data));<br>}<br>  <br>function executeCall(address to, uint256 value, bytes data)   <br>internal returns (bool success) <br>{<br>   assembly {<br>     success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)<br>    }<br> }</pre><h4>Conclusion</h4><p>The<strong><em> parameterized transaction review design pattern</em></strong> outlined here provides a viable alternative inspired by the simple multi-sig and taken to a lower level to allow reviewers to be dynamically chosen for a given data type, <strong><em>based on which contract function is called and which item is being modified</em></strong><em>.</em></p><p>For use within a Colony task, three roles are all we need for each of the Manager, Evaluator, and Worker — but in principle this pattern could be applied to any number of roles and function parameters within a single contract.</p><p>All this was done in the interest of efficiency and flexibility: We are able to have both a single on-chain transaction and a fine-grained set of parameters for multi-signature operations, without wasting time or (gas) money.</p><p>If you’re interested in this kind of technical discussion and want to know more about parameterized transaction reviews, please reach out with your questions on <a href="https://gitter.im/JoinColony/colonyNetwork">Gitter</a>, or post a question in our forums at <a href="https://build.colony.io/">build.colony.io</a> — and if you’d like to, contribute to the <a href="https://github.com/JoinColony/colonyNetwork">colonyNetwork</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbXcvLdWaAL6D_EK4oTEUA.jpeg" /></figure><p>Elena Dimitrova is a Solidity developer.</p><p>She was a corporate warrior in a previous life, but left her high heels and life in London to go backpacking for a year before falling in love with Ethereum and joining Colony.</p><p>She now lives in Bulgaria where, while not writing smart contracts or helping in the Truffle Gitter channel, she goes off-roading in her Jeep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*Z1NuteXxze6ba5BxAGYTIw.png" /></figure><p>Colony is a platform for open organisations.</p><p>Join the discussion on <a href="https://build.colony.io/">Discourse</a>, follow us on <a href="http://twitter.com/joincolony">Twitter,</a> sign up for (occasional) <a href="http://colony.io/">email updates</a>, or if you’re feeling old-skool, drop us an <a href="/service/mailto:hello@colony.io">email</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f0cdc40479" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/parameterized-transaction-reviews-11f0cdc40479">Parameterized Transaction Reviews</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Colony sale contract and the CLNY Token]]></title>
            <link>https://medium.com/colony/colony-sale-contract-and-the-clny-token-3da67d833087?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da67d833087</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Thu, 19 Oct 2017 12:35:05 GMT</pubDate>
            <atom:updated>2017-10-19T12:35:05.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSDuw67OmtOW5qm8CCS2vA.jpeg" /></figure><p>Although the unfortunate reality of regulatory attitudes to token sales has led us to postpone the Colony Token sale until next year, we think it’s worthwhile to open-source our sale code to help others who might be looking for resources on token sale design. (You can read more about the decision in our <a href="https://blog.colony.io/the-colony-token-sale-7ac14c845bc0">recent announcement</a>.)</p><p>This article provides an overview of the Colony Token Sale contracts implementation at <a href="https://github.com/JoinColony/colonySale">https://github.com/JoinColony/colonySale</a></p><p>We wanted to create a sale which was simple to understand, did not require pre-registration, and would not result in selling out rapidly to just a few accounts. At the same time, we didn’t want the amount it was possible to raise to be totally unbounded.</p><p>We chose to go with a simple soft cap: if the soft cap is hit, then the sale closes after the greater of either three hours, or the time taken to hit the soft cap, up to a maximum of 24 hours.</p><p>The core principles followed in the design were: <em>security</em>, <em>simplicity</em> and <em>upgradability</em>. Additionally, we strove to minimise network impact and gas costs for buyers.</p><p>For more on the sale requirements we implemented, see the repo <a href="https://github.com/JoinColony/colonySale/issues?q=is%3Aissue+is%3Aclosed">issues list</a>.</p><h3>Credit</h3><p>The Ethereum development community is based on an ethos of collaboration. Credit goes out to the people and organisations responsible for the contracts we reused and the ideas that influenced this implementation.</p><p><a href="https://github.com/ownage-ltd/ether-router/">EtherRouter design pattern</a> — by Ownage<br>This pattern utilises solidity assembly for low-level routing of calls and was used to implement our static address and fully upgradable token. Implementation details in the “Upgradable Token” section below.</p><p><a href="https://github.com/dapphub/dappsys-monolithic">ERC20 Token, Math and Authorisation contracts</a> — by DappHub<br>The Colony Token reuses the <a href="https://github.com/dapphub/ds-token">DS-Token</a> implementation in combination with the aforementioned EtherRouter pattern. We also extensively reuse the safe arithmetic functions of <a href="https://github.com/dapphub/ds-math">DS-Math</a> as well as the <a href="https://github.com/dapphub/ds-auth">DS-Auth</a> permissions implementation.</p><p><a href="https://github.com/ConsenSys/MultiSigWallet">MultiSig Wallet</a> — by Gnosis / Consensys<br>Developed for the Gnosis crowd sale, see overview here<br><a href="https://blog.gnosis.pm/release-of-new-multisig-wallet-59b6811f7edc">https://blog.gnosis.pm/release-of-new-multisig-wallet-59b6811f7edc</a></p><p>Statement following the discovery of the Parity MultiSig vulnerability <a href="https://blog.gnosis.pm/the-gnosis-multisig-wallet-and-our-commitment-to-security-ce9aca0d17f6">https://blog.gnosis.pm/the-gnosis-multisig-wallet-and-our-commitment-to-security-ce9aca0d17f6</a></p><p><a href="https://medium.com/@weka/token-sales-done-better-funfair-d38c07a03c0b">Token sales done better</a> — by Nick Johnson <br>This article kicked off a very productive internal discussion that led to the focus on lowering the overall network impact. See “Gas cost optimisation and the phantom finney” section below.</p><h3>Contract Design</h3><p>In line with our main principles, the main <em>ColonyTokenSale.sol</em> contract inherits nothing more than the <em>DS-Math</em> contract for safe arithmetics and has just 4 core functions in addition to the fallback and emergency-only start/stop sale functions.</p><h4>Core functions:</h4><ul><li>buy() — called by the payable fallback function which firstly forwards the contribution to the Colony MultiSig wallet, then adds the msg.value to the current user’s contribution tally, and finally updates the totalRaised amount.</li></ul><p>Note that the single transaction which crosses the softCap value will execute additional logic to determine whether the sale endBlock will change.</p><ul><li>finalize() — will execute successfully only once after the sale endBlock has been reached to check whether the sale was successful, if so, it will mint and distribute the preallocated tokens to purchasers, team members and the network fund. It also allocates Token grants for the Colony Foundation and Team pool.</li><li>claimPurchase() —calculate and transfer the purchased tokens to the buyer. This function is going to be called by Colony for each buyer in order to issue the CLNY tokens after the sale is finalised.</li><li>claimVestedTokens() — claim any vested tokens from the token grants created when sale is finalised.</li></ul><h4>Emergency functions:</h4><p>The stop() and start() functions are switching a boolean flag to indicate whether the sale is stopped in case of an emergency. This safety switch is a common pattern in ICOs guarding against attacks.</p><h3>Gas cost optimisation and the phantom finney</h3><p>In earlier versions of the sale contract, gas prices for buy transactions were at around ~120,000 gas which was far too high.</p><p>The first way to reduce cost for CLNY purchasers was by refactoring out token issuance from the buy() function. Now, the claimPurchase() function is run once for every buyer after the sale concludes, and that gas is paid by Colony, saving ~185,252 gas for each buyer.</p><p>After that reduction, we noticed another discrepancy:</p><p>Changing a value from zero to non-zero SSTORE operation incurs an additional 20,000 gas. In the sale contract, the first time the buy()function is called, the totalRaised value needed to be changed from 0to some value — this meant that the first buy() transaction ended up with a gas cost of around 35,000 more than all subsequent buy() calls.</p><p>It seemed like bad luck to pass this cost onto the most eager and luckiest of CLNY buyers, and also would have required us to advise buyers to set their gas limits higher than expected. So, a workaround was devised:</p><p>The totalRaised value is set initially to 1 finney, eliminating the extra cost from the first buyer. The ‘phantom finney’ is then subtracted from totalRaised when the finalize() function is called.</p><p>See commit <a href="https://github.com/JoinColony/colonySale/commit/3ab46c65153c5bae10f8d840b9398434e2f6a2ea">3ab46c65153c5bae10f8d840b9398434e2f6a2ea</a> for more information.</p><p>The buy() transaction now consumes at most 56,944 gas.</p><p>Note that all but two buy() transactions actually cost just 41,994 gas. The two that differ are the very first buy() transaction (56,994 gas) and the one that executes the endBlock update logic (53,618).</p><p>The 20K gas the phantom finney saves in the first transaction has a much wider impact than the 2 cents it saves the first buyer. It helps to lower the total impact of the token sale on the network. Although the block gas limit has been increasing, the <a href="https://etherscan.io/chart/pendingtx">transactions queue still tend to stay high</a> especially during a popular ICO.</p><p>Assume that there are 10,000 buy transactions in queue, and that each of them sends 20K more gas than their actual cost. Because gas is used by miners to fill blocks, about 21 fewer buy transactions would make it in to each block.</p><p>That would mean that for every 10,000 buy transactions, the network would use ~42 extra blocks to process.</p><p>If we were to include the token minting and transfer calls that will jump up to ~110 extra blocks (calculated with the <a href="https://etherchain.org/charts/gasLimit">current block gas limit of ~6,500K</a>).</p><h3>Token Upgradability</h3><p>The third pillar we built the code on was <em>upgradability.</em> This is key for the Colony Token as it will undergo future developments as described in the <a href="http://swarm-gateways.net/bzz:/whitepaper.joincolony.eth">Colony Whitepaper</a>, yet the token address must stay static for clients and exchanges to reference.</p><p>Our implementation is based on the <a href="https://github.com/ownage-ltd/ether-router/">EtherRouter design pattern</a> which uses assembly level delegatecall to forward calls to the upgradable Token contract via a simple, immutable EtherRouter contract that retains its address over time. The Resolver contract holds the token address and function signatures and serves as a routing repository for the token functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*YQnPQRc6XJXVgbJlXrSjmg.png" /><figcaption>Colony Token call flow</figcaption></figure><p>In addition<em> </em>the<em> MultiSigWallet.sol </em>provides the control over the Token upgrade.</p><h3>Contract Testing and Reviews</h3><p>The <em>ColonyTokenSale.sol</em> and <em>Token.sol</em> contracts (including <em>EtherRouter.sol </em>and <em>Resolver.sol</em>) have been tested using truffle/testrpc setup, see <a href="https://github.com/JoinColony/colonySale#testing">https://github.com/JoinColony/colonySale#testing</a></p><p>We maintain <strong>100% code coverage</strong> in tests, automated using <a href="https://github.com/sc-forks/solidity-coverage">solidity-coverage</a>.</p><p>Additional, contracts have been linted using <a href="https://github.com/duaraghav8/Solium">Solium</a> which checks against Solidity style guide.</p><p>Code has been audited by DappHub:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d2a2840d0d666fd55331898a0c85af4/href">https://medium.com/media/3d2a2840d0d666fd55331898a0c85af4/href</a></iframe><p>Finally, for the love of ETH, and all that is decentralised, please don’t use this contract to sell pre-functional tokens. If you need to raise money, use <a href="https://blog.colony.io/a-simple-agreement-for-future-tokens-or-equity-b8ef08608347">this</a> or <a href="https://saftproject.com/#saft-whitepaper">this</a> with people you approach directly instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbXcvLdWaAL6D_EK4oTEUA.jpeg" /></figure><p>Elena is a Solidity developer.</p><p>She was a corporate warrior in a previous life, but left her high heels and life in London to go backpacking for a year before falling in love with Ethereum and joining Colony.</p><p>She now lives in Bulgaria where, while not writing smarter contracts or helping in the Truffle Gitter channel, she goes off-roading in her Jeep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3kBD0oeWdu58kaXTiPPHSQ.png" /></figure><p>Colony is a platform for open organisations.</p><p>Follow us on <a href="http://twitter.com/joincolony">Twitter,</a> sign up for (occasional) <a href="http://colony.io/">email updates</a>, or if you’re feeling old skool, drop us an <a href="/service/mailto:hello@colony.io">email</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3da67d833087" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/colony-sale-contract-and-the-clny-token-3da67d833087">Colony sale contract and the CLNY Token</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token-weighted voting implementation Part 3]]></title>
            <link>https://medium.com/colony/token-weighted-voting-implementation-part-3-821dde0a674b?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/821dde0a674b</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[dao]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Fri, 11 Nov 2016 13:36:18 GMT</pubDate>
            <atom:updated>2016-11-11T13:36:18.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GKw4PJr_VQTk5K_fzTe8g.jpeg" /></figure><h4>Token Locking</h4><p>This is the last of a 3-part article which presents the Solidity-based implementation of the <a href="https://blog.colony.io/towards-better-ethereum-voting-protocols-7e54cb5a0119#.30b4usja3">Token weighted voting protocol</a>.</p><p>In <a href="https://blog.colony.io/token-weighted-voting-implementation-part-2-13e490fe1b8a#.ozefgz473">part 2 of this article</a> we concluded by defining the <em>isAddressLocked</em> function in our <em>VotingLibrary</em> which is key to the implementation of the token locking logic we focus on here. Further on, we define the algorithm of revealing and counting secret votes as well as token unlocking.</p><h4>Token locking</h4><p>Our token contract implementation is based on the E<a href="https://github.com/ethereum/EIPs/issues/20">RC #20 standard</a> where there are two functions that enable token transfers: <em>transfer</em> and <em>transferFrom</em>. To enable token locking, we extend these functions with the following logic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*htqjQYVTbouCdEbn." /><figcaption>Token locking logic</figcaption></figure><p>Once <em>transfer</em> is called, we first establish whether the sender or recipient addresses are locked via the <em>isAddressLocked</em> function in our Voting contract, described in <a href="https://blog.colony.io/token-weighted-voting-implementation-part-2-13e490fe1b8a#.ozefgz473">part 2 of this article</a>.</p><p>In the case when the sender is locked, we fail the transfer. If however the recipient is locked, we hold the transfer amount in an <em>onHoldBalance. </em>After the user reveals their vote, thus unlocking their tokens, that <em>onHoldBalance</em> is transferred to their available balance. The held balance ‘read’, ‘write’ and ‘transfer to balance’ functions are defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75f6f77309d4a4979c9b6dd0c263ae99/href">https://medium.com/media/75f6f77309d4a4979c9b6dd0c263ae99/href</a></iframe><p>The gas cost changes resulting from the additional checks we introduced, show <em>transfer</em> function gas cost has increased only by ~4,500 gas (measured at 53559 before, 58146 after) or roughly 8.5%.</p><h4>Reveal vote transaction</h4><p>This algorithm requires users to always reveal their votes, even if the reveal period has expired. When the <em>pollCloseTime</em> is reached, every user who had voted in that particular poll has their tokens locked, essentially the <em>isAddressLocked</em> function called for their address returns <em>true</em>. This entails that all token <em>transfer</em> calls they make, as per above, will fail and any transfers tokens they receive, will be put on hold. This is mitigated by the fact that a user can unlock their tokens immediately after the poll closes by revealing their vote. This <em>revealVote</em> transaction is detailed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/0*_CYr-vRy0sZgDTJX." /><figcaption>Reveal vote logic</figcaption></figure><p>This is <em>token-weighted </em>voting, so firstly we retrieve the user token balance as this affects how we count the vote .</p><p>Secondly we validate the state by checking that the poll has closed and the vote secret is the same as the one submitted when the user voted. This is done by comparing the saved secret to the hash of the salt and pollOptionId the user has voted on. For details of generating the secret vote, see Secret voting in <a href="https://blog.colony.io/token-weighted-voting-implementation-part-2-13e490fe1b8a#.ozefgz473">part 2 of this article</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaba30ce0d14b1aa0357cefddb3c0468/href">https://medium.com/media/eaba30ce0d14b1aa0357cefddb3c0468/href</a></iframe><p>Once the vote is revealed and validated, we determine whether to count it in the final poll results. This is determined again by the poll status property, which if <em>resolved</em>, means the admin has taken the final poll results and counting votes is over. Otherwise, the votes on the decision are incremented appropriately based on the current balance of the revealing user which we had already retrieved in the first part of this transaction. For example, if a user A with 1200 tokens had voted for option X, then the total count of poll option X is increased by 1200 once user A submits their <em>revealVote</em> transaction (and before the poll is resolved).</p><p>We then continue to unlock the user account for token transfers and any tokens that have been on hold are transferred to their standard available balance. Note that tokens are only released once no unrevealed votes remain. As it could be the case that there are other votes left to be revealed, in which case the current revealVote transaction doesn’t unlock the account.</p><h4>Devcon2</h4><p>This implementation was <a href="https://www.youtube.com/watch?v=zSF5fGPG4Ro&amp;index=1&amp;list=FLtyfiplFEU8Veu9c9e-DqCA">presented at Devcon2</a> (which is where the featured photos of the Shanghai skyline are from, in case you wonder about the connection between China and democratic voting protocols).</p><p>The <a href="https://www.youtube.com/watch?v=zSF5fGPG4Ro&amp;index=1&amp;list=FLtyfiplFEU8Veu9c9e-DqCA">recording</a> from our presentation there gives a good high level overview of the theory and practice of this implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821dde0a674b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/token-weighted-voting-implementation-part-3-821dde0a674b">Token-weighted voting implementation Part 3</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token-weighted voting implementation Part 2]]></title>
            <link>https://medium.com/colony/token-weighted-voting-implementation-part-2-13e490fe1b8a?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e490fe1b8a</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[dao]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Thu, 29 Sep 2016 06:32:38 GMT</pubDate>
            <atom:updated>2016-11-11T13:37:37.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uxvqHbjvF2s22EbcRWGORQ.jpeg" /></figure><h4>Secret voting and the double linked list</h4><p>This is the second of a 3-part article which presents the Solidity-based implementation of the <a href="https://blog.colony.io/towards-better-ethereum-voting-protocols-7e54cb5a0119#.30b4usja3">Token weighted voting protocol</a>.</p><p>Here, we continue to define the double linked list used to manage vote secrets and we dive into the voting implementation itself as well as the logic behind determining if an address is locked.</p><h4>Vote secrets data structure — the double linked list</h4><p>Vote secrets are stored in a double linked list. Each entry consists of the poll id, vote secret and is ordered by poll close time. The list contains only the unrevealed vote secrets for a user, i.e. when a vote is revealed, it is removed from this list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*_PBlDSQpJzAl3DDt." /><figcaption>Double linked list of vote secrets ordered by poll close time</figcaption></figure><p><strong>Zero-entry item<br></strong>The list implementation uses a helper <em>zero-entry item</em> where the <em>previousItem</em> link points to the last item in the list and the <em>nextItem </em>link points to the first item in the list, thus closing the list structure.</p><p>This design gives us less edge cases as we don’t need to track variables such as the first item in the list, the item count or cater for special cases where we’re inserting at the start or at the end of the list.</p><p><strong>Design for poll votes that close at the same time<br></strong>Additionally, we need to design support for cases where two or more polls close at the same time, thus having conflicting <em>pollCloseTime</em> in the ordered list. We solve this by having a second <strong>inner</strong> double linked list. We move the <em>pollId</em> and <em>vote secret</em> into this inner list, leaving the <strong>outer</strong> list to just holding <em>pollCloseTime</em> information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*J985yxYexQ_AYGdlTDiYCw.png" /></figure><p>Example design for this above, models a user having voted 5 times in polls with Ids: 1, 5, 8, 12 and 14. Polls 1 and 5 close at the same time at timestamp 10, while the other polls (8, 12 and 14) close at unique times, respectively 52, 123 and 456 and thus have just a single vote secret entry against them in the inner list.</p><p>The storage data model of the key/value pairs for two linked lists can therefore be modelled as follows</p><pre>//Doubly linked list holding polls closeTimes<br>sha3(&quot;Voting&quot;, userAddress, pollCloseTime, &quot;prevTimestamp&quot;) =&gt; uint256 prevTimestamp</pre><pre>sha3(&quot;Voting&quot;, userAddress, pollCloseTime, &quot;nextTimestamp&quot;) =&gt; uint256 nextTimestamp<br></pre><pre>//Doubly linked list holding vote secrets<br>sha3(&quot;Voting&quot;, userAddress, pollCloseTime, &quot;secrets&quot;, pollId, &quot;secret&quot;) =&gt; bytes32 secret</pre><pre>sha3(&quot;Voting&quot;, userAddress, pollCloseTime, &quot;secrets&quot;, pollId, &quot;prevPollId&quot;) =&gt; uint256 pollId</pre><pre>sha3(&quot;Voting&quot;, userAddress, pollCloseTime, &quot;secrets&quot;, pollId, &quot;nextPollId&quot;) =&gt; uint256 pollId</pre><p><strong>Sorting double linked lists <br></strong>In the case where the smart contract is responsible for finding the position in the list for a new vote, it’s possible that in the transaction inserting the vote runs out of gas, as we iterate through items to find the right order.</p><p>We solve this by delegating to the user the job of providing us the position where their vote needs to be inserted. We validate the position info they give us and do the insert.</p><p>In addition to lower gas costs, as we don’t sort on the blockchain, this approach has the added benefit of a fixed and predictable transaction cost for adding a vote secret to the list, as storage cost is fixed.</p><h4>Secret voting</h4><p>Whenever a user makes a vote, first they must establish what their precommitted vote secret is to be. They do this by finding the Keccak hash of a salt value and the chosen poll option Id. This is the equivalent of calling <em>sha3(salt, pollOptionId);</em> in Solidity.</p><p>The salt is required so that the user’s vote cannot be discerned pre-reveal. The salt is revealed during the reveal phase, and so should not be sensitive, but it should be unique for every vote and not have to be remembered or chosen by the user. The voteID signed with the user’s private key, for example, would meet these requirements, as would the brief signed with the user’s private key, which would have the additional benefit of allowing the user to prove what they voted on, as well as the direction they voted.</p><p>The user then calls the vote function,</p><pre>function submitVote(<br>    uint256 pollId,<br>    bytes32 secret,<br>    uint256 prevTimestamp,<br>    uint256 prevPollId)</pre><p>which has four arguments:</p><p><em>uint256 pollId — </em>Id of the poll which they’re voting on<br><em>bytes32 secret</em> — The secret string described above<br><em>uint256 prevTimestamp</em> — The timestamp that the secret should be inserted after for the outer list (of poll closing times) to remain correctly sorted. If this is 0, then the current element is the first element in the linked list that comes after the <em>zero-entry item</em>. <br><em>uint256 prevPollId</em> — The poll Id that the secret should be inserted after for the inner list (of poll ids and vote secrets) to remain correctly sorted.</p><p>A number of validations then take place before the secret is added, to ensure the poll is open and its closingTime hasn’t past as well as the position in the outer and inner lists is correct.</p><h4>isAddressLocked function</h4><p>The purpose of the double linked lists are two fold: firstly as described above, to store unrevealed votes and secondly, to determine if an address is locked.</p><p>An address is defined as locked, if there is at least 1 vote a user has to reveal, i.e. at least one vote for poll which has closed.</p><p>This check is implemented in a function, namely <em>isAddressLocked(address) </em>which looks at the outer list of pollCloseTimes, takes the first item in the list (after the zero-entry item) and compares the <em>now</em> block timestamp against it. Since the list is ordered by pollCloseTimes, we guarantee that if the first item in the list is less than the now timestamp, i.e. the poll close time for that first item has passed, there is at least one vote secret which needs to be revealed and therefore the user address is locked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*zqhWEnh9t7wJcMZXXgrZPA.png" /><figcaption>Sample scenario for a locked address</figcaption></figure><p>This model can be implemented as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b178679ac9f9042df280c071c71b9e7/href">https://medium.com/media/3b178679ac9f9042df280c071c71b9e7/href</a></iframe><p><a href="https://medium.com/@elena_di/token-weighted-voting-implementation-part-3-821dde0a674b#.nidt64l3v">In the third and final article we’ll examine how the isAddressLocked function above is used to extend the token implementation. We also look at the mechanics of revealing a vote</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e490fe1b8a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/token-weighted-voting-implementation-part-2-13e490fe1b8a">Token-weighted voting implementation Part 2</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token-weighted voting implementation Part 1]]></title>
            <link>https://medium.com/colony/token-weighted-voting-implementation-part-1-72f836b5423b?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/72f836b5423b</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[dao]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Mon, 19 Sep 2016 14:55:45 GMT</pubDate>
            <atom:updated>2016-09-29T06:34:31.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYyVacNmpPO6q5kgpzgSgw.jpeg" /></figure><h4>Poll Lifecycle</h4><p>This is the first of a 3-part article which presents the Solidity-based implementation of the <a href="https://blog.colony.io/towards-better-ethereum-voting-protocols-7e54cb5a0119#.30b4usja3">Token weighted voting protocol</a>. I am presenting the end-to-end implementation overview of this at DevCon2 and these 3 articles aim to go into the detail of this. <br>Here, we examine the lifecycle of a poll and its data structure.</p><h4>High-level contract design</h4><p>Before we go into the implementation details, it’s necessary to understand the Colony contract design at a high level.</p><p>The Colony contract itself serves as the interface to the user.</p><p>The library layer encapsulates the business logic for different domains, e.g. TokenLibrary contains the logic for managing Colony tokens, Voting library contains the poll and votes management logic etc. The Security and Task library in the diagram below are greyed out as they’re not directly relevant in the context of this article but they form an integral part of the Colony network.</p><p>While we use libraries to encapsulate business logic, we use a generic storage contract to persist Colony data, e.g. storing information about the token balances, polls and votes etc.</p><p>This contracts design is established following our chosen approach for <a href="https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88#.innhmpe3k">writing upgradable contracts</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*JppDAwggeC6fKDFuu4WHsg.png" /><figcaption>Colony high level contract design</figcaption></figure><p>In this first article on poll management, all functionality is encapsulated into the Voting Library implementation.</p><h4>Poll data structure</h4><p>Similar to the traditional sense of what makes up a poll, we have implemented the following properties:</p><ul><li><em>description</em> — contains the poll question itself, e.g. “Should Scotland be an independent country?”</li><li><em>poll options</em> — there should be a minimum of 2 options for each poll, e.g. “Yes”, “No”</li><li><em>start time</em> — the point in time when the poll opens for voting</li><li><em>close time</em> — the point in time when the poll closes for voting</li><li><em>poll status</em> — a poll goes through the stages of being <em>created</em>, <em>active (open for votes or revealing votes) </em>and <em>resolved</em></li></ul><p>These are implemented as <em>bytes32</em> key mappings to their respective EterenalStorage-supported types.</p><pre><strong>bytes32 Key</strong>                                  <strong>Mapped value type</strong><br>sha3(&quot;Poll&quot;, pollId, &quot;description&quot;)         =&gt; string<br>sha3(&quot;Poll&quot;, pollId, &quot;option&quot;, idx)         =&gt; string<br>sha3(&quot;Poll&quot;, pollId, &quot;startTime&quot;)           =&gt; uint256<br>sha3(&quot;Poll&quot;, pollId, &quot;closeTime&quot;)           =&gt; uint256<br>sha3(&quot;Poll&quot;, pollId, &quot;status&quot;)              =&gt; uint256</pre><p>In addition, there are two global properties we maintain for the purpose of enumerating through polls and poll options. We keep a count of polls and poll options and never delete them. Thus we maintain a “poll count” global property which helps us keep track of this and used to generate the ID of the next item when it’s created.</p><pre><strong>bytes32 Key</strong>                                  <strong>Mapped value type<br></strong>sha3(&quot;PollCount&quot;)                           =&gt; uint256<br>sha3(&quot;Poll&quot;, pollId, &quot;OptionsCount&quot;)        =&gt; uint256</pre><h4>Poll Lifecycle</h4><p>Polls can be managed by admins only and their lifecycle is a one-way staged process as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*JT9KczxgN7Prtfeak8LQvw.png" /><figcaption>Poll Lifecycle</figcaption></figure><p>To ensure the stages are sequential, we make use of a modifier to ensure the poll is currently with the correct status.</p><pre>modifier <strong>ensurePollStatus</strong>(uint256 pollId, uint256 pollStatus)<br>{<br>   var currentStatus = getUIntValue(sha3(“Poll”, pollId, “status”));<br>   if (pollStatus != currentStatus) { throw; }<br>   _<br>}</pre><p>The following poll management functions have been implemented in our Voting library, which set the required properties outlined above, i.e. <em>description</em>,<em> poll option</em>, <em>open</em> and <em>close times</em> and <em>status</em>:</p><pre>function <strong>createPoll</strong>(string description) {...}</pre><pre>function <strong>addPollOption</strong>(uint256 pollId, string pollOptionDescription)<br>  ensurePollStatus(pollId, 0)<br>  returns (bool) {...}</pre><pre>function <strong>openPoll</strong>(uint256 pollId, uint256 pollDuration)<br>  ensurePollStatus(pollId, 0)<br>  returns (bool) {...}</pre><pre>function <strong>resolvePoll</strong>(address _storageContract, uint256 pollId)<br>  ensurePollStatus(pollId, 1)<br>  returns (bool) {...}</pre><p>Let’s run through a sample call sequence for this:</p><pre>colony.createPoll(&quot;Should the United Kingdom remain a member of the EU?&quot;);<br>colony.addPollOption(1, &quot;Yes&quot;);<br>colony.addPollOption(1, &quot;No&quot;);</pre><pre>colony.openPoll(1, 24);</pre><pre>// forward time past the poll close time</pre><pre>colony.resolvePoll(1);</pre><h4>Poll close time</h4><p>There is an additional status of poll closed which gets determined by the poll <em>closeTime</em> property, i.e.</p><pre>if (closeTime &gt; now) =&gt; Poll is closed</pre><p>This is set in the <em>openPoll</em> function as:</p><pre>now + pollDuration * 1 hours</pre><p>Poll duration is set in hours as the lowest denominator for poll duration time, however you can easily adjust that to minutes, seconds, days etc.</p><h4><strong>Poll Voting</strong></h4><p><a href="https://blog.colony.io/token-weighted-voting-implementation-part-2-13e490fe1b8a#.vg89edh5u">In the second article we will examine the Secret Voting implementation and the double linked lists data structures we use to manage these.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72f836b5423b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/token-weighted-voting-implementation-part-1-72f836b5423b">Token-weighted voting implementation Part 1</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing robust smart contracts in Solidity]]></title>
            <link>https://medium.com/colony/writing-more-robust-smart-contracts-99ad0a11e948?source=rss-899aa52b377e------2</link>
            <guid isPermaLink="false">https://medium.com/p/99ad0a11e948</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Elena Gesheva]]></dc:creator>
            <pubDate>Wed, 10 Aug 2016 13:43:09 GMT</pubDate>
            <atom:updated>2016-08-31T08:13:41.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVwM1wXB5g063dmF-mjpkg.jpeg" /></figure><p>Before contract function code executes, it’s a good idea to validate who triggered it and what inputs are given.</p><p>Here we build on the Solidity documentation and our own practice to demonstrate a few methods for validating <em>caller</em> and <em>data</em> of inter-contract communication, in both contract-to-contract and user-to-contract calls.</p><blockquote>Restricting access is a common pattern for contracts. Note that you can never restrict any human or computer from reading the content of your transactions or your contract’s state. [..] You can restrict read access to your contract’s state by <strong>other contracts</strong>.</blockquote><blockquote>Furthermore, you can restrict who can make modifications to your contract’s state or call your contract’s functions. The use of <strong>function modifiers</strong> makes these restrictions highly readable.</blockquote><p>Building on the <a href="http://solidity.readthedocs.io/en/latest/common-patterns.html">Solidity common patterns</a> above, we make extensive use of <a href="http://solidity.readthedocs.io/en/latest/common-patterns.html#example">function modifiers</a> to ensure the validity of function calls in terms of who the caller is as well as what data is.</p><h3>Validating caller</h3><p>For call authorisation we can start with a simple scenario where the creator of the contract is the only one we’d like to allow to make certain restricted ‘owner-only’ calls, e.g. changing the owner, writing to storage, or killing the contract.</p><p>The <em>Ownable.sol </em>contract below defines the basis of implementing such contract ‘ownership’ and owner-only function modifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7da5de0f7fb641a8359c5c45dfcb5766/href">https://medium.com/media/7da5de0f7fb641a8359c5c45dfcb5766/href</a></iframe><p>Any contract which inherits <em>Ownable</em> will have owner set to the caller at the time of its creation, and any of its functions implementing <em>onlyOwner</em> modifier will not accept calls from another account. Note that the creator can be a user or another contract.</p><p>To put that in context, we use the sample contract code from our previous post on <a href="https://blog.colony.io/writing-upgradeable-contracts-in-solidity-6743f0eecc88#.tze3zhi1f">implementing upgradable contracts</a> — specifically the main two contracts: ‘<em>Parent</em>’ and ‘<em>Organisation</em>’. To recap those, <em>Parent</em> contract is used to create, store, retrieve and upgrade <em>Organisation</em> instances. <em>Organisation</em> interacts with an instance of <em>EternalStorage</em> via <em>ProposalsLibrary</em> and also with an <em>ITokenLedger</em> implementation instance.</p><p>We’ll demonstrate how to secure <em>Organisation</em> contract’s storage to allow owner-only write permissions.</p><h4><strong>Securely writing to Storage</strong></h4><p><em>EternalStorage</em> contract is used to read and write values of different types to storage. Every <em>Organisation</em> contract has an instance of <em>EternalStorage</em> to which only it should be able to write. In this case the owner of <em>EternalStorage</em> should be a contract (<em>Organisation</em>) rather than a user. We do not want users to be interacting directly with storage as all the business rules for data are abstracted away from it.</p><p>For the implementation we simply inherit <em>Ownable</em> and decorate all storage write functions with the <em>onlyOwner </em>modifier, e.g. <em>setUIntValue, setStringValue </em>etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8d5b9b52d15e6ff8fda48851157a721/href">https://medium.com/media/d8d5b9b52d15e6ff8fda48851157a721/href</a></iframe><p>We need to ensure the <em>owner</em> of <em>EternalStorage</em> instance is the <em>Organisation</em> contract. The easiest way to ensure that, is to let it create it. See constructor below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8593b1908526dca5d7313781a3c15022/href">https://medium.com/media/8593b1908526dca5d7313781a3c15022/href</a></iframe><p>Here <em>msg.sender</em> in <em>EternalStorage</em> is the <em>Organisation</em> contract which then becomes the only address allowed to write to storage.</p><p><strong>Note on Libraries:</strong> We use a library contract (<em>ProposalsLibrary</em>) to attach a set of functions to <em>EternalStorage</em>, so effectively message calls flow through the following chain: <em>Organisation</em> -&gt; <em>ProposalsLibrary</em> -&gt; <em>EternalStorage.</em><br>However, since libraries in Solidity pass on the <em>msg.value</em> and <em>msg.sender</em> values, calls to <em>EternalStorage</em> have <em>msg.sender </em>as the <em>Organisation</em> contract address and not <em>ProposalsLibrary</em> address.</p><h4>Securely writing to Storage — extended example</h4><p>Let’s extend the simplified example above to cover our sample scenario of using a <em>Parent</em> contract to create and manage Organisations. We would also like to remove the <em>Organisation</em> contract dependency on <em>EternalStorage </em>just to make our contract lighter. For this we have delegated the role of creating <em>EternalStorage</em> and <em>Organisation</em> to <em>Parent</em> contract, which are both created via the <em>Parent.createOrganisation(bytes32)</em> function. When <em>Parent</em> calls <em>new EternalStorage()</em> it becomes the owner of it as well, so it needs to call <em>Ownable.changeOwner(address)</em> to adjust ownership to the newly created <em>Organisation</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/346a4978f1397302a5d78f3a3df76208/href">https://medium.com/media/346a4978f1397302a5d78f3a3df76208/href</a></iframe><p>This is an example of where <em>EternalStorage</em> ownership change is required due to the more complex initiation process of our contracts.</p><h4>Support for multiple admin accounts</h4><p>Since <em>msg.sender </em>only allows for a single owner per contract, to implement support for multiple admins we can make use of storage to manage a collection of user admin account addresses.</p><p>Below is a helper library which implements the basic functionality of adding and removing admin accounts for a given contract (address).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdaa8baeb93b83991921abacb5ae1b18/href">https://medium.com/media/cdaa8baeb93b83991921abacb5ae1b18/href</a></iframe><p>The <em>isUserAdmin</em> function can then be used in a modifier, just like <em>onlyOwner </em>in our previous example<em>. </em>For instance if we wanted to allow multiple admins in <em>Organisation</em> we can implement this as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/698962ac0d0aadcb725e0f7a44255d9f/href">https://medium.com/media/698962ac0d0aadcb725e0f7a44255d9f/href</a></iframe><h3>Validating data</h3><p>In addition to authorising the call sender, modifiers can be also used to validate the data provided with the call. A sample library of useful modifiers is below, implementing checks for various types, e.g. empty address or zero value integers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6089df7e20c57ab0c2a6fdbabee7dd9/href">https://medium.com/media/f6089df7e20c57ab0c2a6fdbabee7dd9/href</a></iframe><h3>Putting it all together</h3><p>With the armour of authorisation and validation modifiers you can decorate your functions as necessary to ensure that before you execute a function, you have subjected the caller and call data to the utmost scrutiny.<br> <br>Example of such use is in our <em>Organisation.addProposal(bytes32) </em>function which should only allow Organisation admins to create proposals. Additionally we ensure no ether is sent with the request and that we get a non empty key for the proposal being created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0307dec7bbbc84ed777dbe837e96f3e/href">https://medium.com/media/f0307dec7bbbc84ed777dbe837e96f3e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ad0a11e948" width="1" height="1" alt=""><hr><p><a href="https://medium.com/colony/writing-more-robust-smart-contracts-99ad0a11e948">Writing robust smart contracts in Solidity</a> was originally published in <a href="https://medium.com/colony">Colony</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>