<?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[Deepyr - Medium]]></title>
        <description><![CDATA[Blockchain Research &amp; Development for the Decentralised Future - Medium]]></description>
        <link>https://medium.com/deepyr?source=rss----d8a321b08114---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Deepyr - Medium</title>
            <link>https://medium.com/deepyr?source=rss----d8a321b08114---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:52:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/deepyr" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Back to the future!! Testing Solidity through time with Brownie.]]></title>
            <link>https://medium.com/deepyr/back-to-the-future-testing-solidity-through-time-with-brownie-5da4f257e2cb?source=rss----d8a321b08114---4</link>
            <guid isPermaLink="false">https://medium.com/p/5da4f257e2cb</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Adrian Guerrera]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 04:29:43 GMT</pubDate>
            <atom:updated>2020-05-07T09:47:55.961Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>I’ve been having a blast testing some smart contracts I’ve been working on - so much so, I’ve decided to share some of the cool new features discovered in Brownie, including time travel which has blown my mind.</p><p>Brownie is a Python-based development and testing framework for smart contracts on Ethereum. → <a href="https://eth-brownie.readthedocs.io/en/stable/index.html">https://eth-brownie.readthedocs.io/</a></p><p>Aside from being an awesome replacement to truffle, it comes baked with some seriously powerful testing libraries - pytest and hypothesis.</p><h4>Lets do this!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxsF1FSDbjguis%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxsF1FSDbjguis%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxsF1FSDbjguis%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="227" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5ec42f6ea99db13d61142b76ca22c99/href">https://medium.com/media/e5ec42f6ea99db13d61142b76ca22c99/href</a></iframe><p>It all starts with one line</p><blockquote>brownie init</blockquote><p>Few other assumptions for this example: you have a smart contract that you want to test, and it does something over time. It could be accruing interest, vesting tokens over time, FOMO3d etc. In my case, I’ll be going through a crowdsale contract with a start and end date.</p><p>We’ll take a mintable token contract. Any will do. Just put a token contract in the /contracts folder, add your crowdsale contract and we’re good to go. I’ll post the repo I’m working on below as a reference implementation, but for now, lets go ahead and compile.</p><blockquote>brownie compile</blockquote><h4>Time to activate pytest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlIeKPjV6Q_WK-Hge35ZDA.png" /></figure><p>All you have to do is add a .py file in the /tests directory.</p><p>That’s it.</p><p>If you’re familiar with pytests, you can create a conftest.py file which we’ll keep all our deployed contracts and fixtures. Fixtures are reusable objects we’ll be calling each time we go to the future, and back.</p><pre>from brownie import accounts<br>import pytest</pre><pre><strong># Use pytest fixture so we can reuse this</strong><br>@pytest.fixture(scope=&#39;module&#39;, autouse=True)<br>def test_token(Token):<br>    name = &#39;Test Token&#39;<br>    symbol = &#39;TEST&#39;<br>    decimals = 18 <br>    mintable = True<br>    initial_supply = 0<br>    owner = accounts[0]</pre><pre><strong>    # Deploy test_token</strong><br>    test_token = Token.deploy(owner<br>                  , symbol, name<br>                  , decimals<br>                  , initial_supply<br>                  , mintable<br>                  , {&#39;from&#39;: accounts[0]})</pre><pre>    return test_token</pre><p>Here we deployed a contract “Token” that is frozen in time, importantly the scope set to ‘module’ allows you to run tests, but after the function finishes, resets the contract state before the next test.</p><pre>@pytest.fixture(scope=&#39;module&#39;, autouse=True)<br>def frames_crowdsale(Crowdsale, test_token):<br><br>    <strong># Time when you run the test</strong><br>    start_date = rpc.time()    <br>    end_date = startDate + 60*60*24<br>    owner = accounts[0]</pre><pre><strong>    # Deploy crowdsale</strong><br>    crowd_sale = Crowdsale.deploy(test_token<br>               , start_date <br>               , end_date<br>               , {&quot;from&quot;: owner})<br>    <br>   <strong> # Let the crowdsale mint</strong><br>    tx = frame_token.setMinter(<br>               crowd_sale<br>               , {&quot;from&quot;: owner})</pre><pre>    <strong># Test if successful</strong><br>    assert &#39;MinterAdded&#39; in tx.events.</pre><pre>    return crowd_sale</pre><p>That’s kinda cool, we set up two contracts in Brownie, but when will we see some time travel?!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYUTJNDps86gtG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYUTJNDps86gtG%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FYUTJNDps86gtG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="235" frameborder="0" scrolling="no"><a href="https://medium.com/media/56715a048a89b4d6b4fd03310bcef531/href">https://medium.com/media/56715a048a89b4d6b4fd03310bcef531/href</a></iframe><p>Well before we get started, we have just activated pytests, deployed two contracts in a fixture, added the crowd sale as the minter and asserted there indeed was an AddedMinter event. We can now run the tests and check the code coverage - which is pretty - with the following lines.</p><blockquote>brownie test -v</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-B5Ek2s3EsuYTiA1LKH3A.png" /><figcaption>Sample Brownie test output — Not representative of above pseudo code.</figcaption></figure><blockquote>brownie test -coverage</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuLR94zwBXUcLUpN3DOLBg.png" /><figcaption>Brownie shows you code test coverage — I cut the greenest section out for this post.</figcaption></figure><h4>Setting a start and end time</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FdgEIhYAo3lZiE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FdgEIhYAo3lZiE%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FdgEIhYAo3lZiE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/93661aa19c8b48a624a7bfb981e20ee5/href">https://medium.com/media/93661aa19c8b48a624a7bfb981e20ee5/href</a></iframe><p>Previously I would have either test a tiny time window. Or play with Geth and Ganache settings, write out a long perfectly curated script of test transactions to run, avoiding any prior txns errors, restart the node and do it all over again as I develop… I have even heard of someone - deploying to Ropsten, waiting 24 hours and testing again - checking it actually finalized - before deploying to main-net.</p><blockquote>“ok it’s been 24 hours lets make sure it finalised”</blockquote><p>Still, better than no testing at all - but far from ideal. Instead, let’s do a test in Brownie, going forwards in time, then going back in time &amp; run a second test.</p><pre><em>#/tests/test_crowdsale.py</em></pre><pre><strong># Test 1</strong><br>def test_finalise(crowd_sale)<br>   with reverts():            <br>       <strong># error: Crowdsale not yet finished</strong><br>       tx = crowd_sale.finalise()<br>    <br>   <strong># Travel 25hr into the future!</strong><br>   <strong>rpc.sleep(60*60*25) </strong>       <br>    <br>   tx = crowd_sale.finalise({&#39;from&#39;:owner})<br>   <strong># Check if finished</strong>  <br>   assert crowd_sale.finalised() == True</pre><pre><strong># Test 2 - Reset back in time</strong><br>def test_buy_eth(crowd_sale, test_token):<br>    tx = accounts[3].transfer(crowd_sale, &quot;10 ether&quot;)</pre><pre>    <strong># Can still buy tokens!!!</strong><br>    assert &#39;Purchased&#39; in tx.events<br>    assert test_token.balanceOf( accounts[3]) == 10 * 10 **18</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FEnVW9bXB94aw8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FEnVW9bXB94aw8%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FEnVW9bXB94aw8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="189" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e432d8dc00340116d5248f26d6565c/href">https://medium.com/media/62e432d8dc00340116d5248f26d6565c/href</a></iframe><p>There are in fact a number of ways to use Brownie to skip through time. <a href="https://eth-brownie.readthedocs.io/en/stable/core-rpc.html">https://eth-brownie.readthedocs.io/en/stable/core-rpc.htm</a></p><p>After my initial excitement in Gitter, Ben Hauser, the lead developer of Brownie goes to me…</p><blockquote>“You should try it in stateful testing”</blockquote><p>Stateful testing is a gamechanger! Essentially you set up some rules, set up some truths — called invariants — and let it run until it breaks. You don&#39;t have to map out specific user interactions, it tries a number of combinations. It’s fantastic for testing a bunch of edge cases, finding dust, you name it. But it really gets into its own world when you include time travel, as a rule.</p><p><a href="https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html">https://eth-brownie.readthedocs.io/en/stable/tests-hypothesis-stateful.html</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FsLVNldFb2Ck5G%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FsLVNldFb2Ck5G%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FsLVNldFb2Ck5G%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/df8766232f19b103014be1c8f7bcd377/href">https://medium.com/media/df8766232f19b103014be1c8f7bcd377/href</a></iframe><p>As we approach 1.21 Gigawatts, all you need to gather in the pseudo code below is that there are 4 rules for the contract, and one truth that should hold, called an invariant. The truth being, how much the contract should hold.</p><pre><em>#/tests/test_crowdsale.py</em></pre><pre>import brownie<br>from brownie.test import strategy</pre><pre>class StateMachine:</pre><pre>    eth = strategy(&#39;uint256&#39;, max_value = &quot;10 ether&quot;)<br>    sleep = strategy(&#39;uint256&#39;, max_value = 60000)<br>    addr = strategy(&#39;address&#39;)</pre><pre>    def __init__(cls, accounts, contract):<br>        # Initialise the contract<br>        cls.accounts = accounts<br>        cls.contract = contract</pre><pre>    def setup(self): <br>        # Reset each run<br>        self.contributed_usd = 0<br>        self.hardcap_usd = 3000000</pre><pre>    def <strong>rule_1_buyEth</strong>(self,eth):<br>        # Purchase in ETH calcs</pre><pre>    def <strong>rule_2_buyUsd</strong>(self,usd):<br>        # Purchase in dollars</pre><pre>    def <strong>rule_3_sleep</strong>(self,sleep):<br>        rpc.sleep(st_sleep) </pre><pre>    def <strong>rule_4_final</strong>(self, addr):<br>        self.contract.finalised()</pre><pre>    def <strong>invariant</strong>(self):<br>       # compare the contract amount with the local state<br>       assert self.contract.contributedUsd() == self.contributed_usd<br></pre><p>In the reference implementation I go through the logic for each of the rules. I share the rule_3_sleep() as it is simple, yet a powerful addition to the testing. What this means is, as the state machine is going through all the possible combinations, one option is for it to skip ahead in time, eventually ending the crowdsale. If there is some combination of buying, skipping through time or trying to finalize early that causes an error, it will show the exact sequence of steps taken and accounts used to recreate the error.</p><p>Then next step would be to wrap the state_machine in a function, just as you would in a regular test, and let hypothesis do its magic!</p><pre><em>#/tests/test_crowdsale.py</em></pre><pre>def test_state(crowd_sale, accounts, state_machine):</pre><pre><strong>    # This is how many steps and examples you want to try</strong><br>    settings = {&quot;stateful_step_count&quot;: 20<br>              , &quot;max_examples&quot;: 50}</pre><pre>    state_machine( StateMachine<br>              , accounts[0:3]<br>              , crowd_sale<br>              , settings=settings)</pre><p>It will then start to process a bunch of permutations, mixing different rules and checking if it broke the invariant. The moment I first got it running it had a bug and showed a step by step, each transaction how it broke the invariant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxY1b2iRuWiHd8O9c82AxQ.png" /><figcaption>You can skip property tests and only run stateful tests with &gt;brownie test— stateful true</figcaption></figure><p>Another cool example of a state machine using hypothesis is this: <a href="https://hypothesis.works/articles/how-not-to-die-hard-with-hypothesis">Solving the 3l jug puzzle from Die Hard 3</a>.</p><p>Combining both property based testing and state based testing is crucial for complex code that deals with state change over time. Now 30% better with Brownie, pytest, hypothesis and time travel!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3Z1b90nxAVj7C7YS5G%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3Z1b90nxAVj7C7YS5G%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3Z1b90nxAVj7C7YS5G%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/c66d882cc5343eee45e6702e412d4301/href">https://medium.com/media/c66d882cc5343eee45e6702e412d4301/href</a></iframe><p>State based testing is a powerful tool essential for developers to think about as part of their testing/CI, as well as for preparing for, and running security audits on smart contract code.</p><p>If you’re going to deploy on mainnet, please do some testing and share your test suite before locking up other peoples money. Users will both have increased confidence in your contracts, and best case, developers will highlight errors in your test suite.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FagrLJjmKdow92%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FagrLJjmKdow92%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FagrLJjmKdow92%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6edc9bac5d74e1b0248eed5f4569348/href">https://medium.com/media/d6edc9bac5d74e1b0248eed5f4569348/href</a></iframe><p>Thanks for reading. Below is my half baked example of Brownie on a project I’m currently building. Tests are in the /tests directory. I would appreciate any feedback in the spirit of open source and collective collaboration.</p><p><a href="https://github.com/apguerrera/DreamFrames">apguerrera/DreamFrames</a></p><p>Big thanks to the super human <a href="https://medium.com/u/1f38e34e130f">Ben Hauser</a> and all the contributors of <a href="https://github.com/iamdefinitelyahuman/brownie">Brownie</a> for making such a joy of a tool for testing. Keep up the great work!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5da4f257e2cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepyr/back-to-the-future-testing-solidity-through-time-with-brownie-5da4f257e2cb">Back to the future!! Testing Solidity through time with Brownie.</a> was originally published in <a href="https://medium.com/deepyr">Deepyr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interacting with Ethereum using web3.py and  Jupyter Notebooks]]></title>
            <link>https://medium.com/deepyr/interacting-with-ethereum-using-web3-py-and-jupyter-notebooks-e4207afa0085?source=rss----d8a321b08114---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4207afa0085</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Deepyr Tech]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 05:54:49 GMT</pubDate>
            <atom:updated>2019-01-21T12:55:43.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>Interacting with Ethereum using web3.py and Jupyter Notebooks</h3><h4>Step by step guide for setting up a Jupyter notebook, connecting to an Ethereum node and deploying a Smart Contract.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPM8uEEFYUO-QPwXnlXjNQ.png" /></figure><h4>Step 1- Installing Dependencies</h4><p>Grab a copy of the files, we will be using in this example, then install the following dependencies, if you haven’t already.</p><p><a href="https://github.com/apguerrera/ethereum-notebooks">apguerrera/ethereum-notebooks</a></p><p><strong>Jupyter Notebooks</strong></p><pre>pip3 install --upgrade pip<br>pip3 install jupyter</pre><p><a href="https://jupyter.readthedocs.io/en/latest/install.html">Installing Jupyter Notebook - Jupyter Documentation 4.1.1 alpha documentation</a></p><p><strong>Installing Web3.py</strong></p><p><a href="https://web3py.readthedocs.io/en/stable/quickstart.html">Quickstart - Web3.py 5.28.0 documentation</a></p><pre>pip install web3</pre><p><a href="https://web3py.readthedocs.io/en/stable/troubleshooting.html#setup-environment">https://web3py.readthedocs.io/en/stable/troubleshooting.html#setup-environment</a></p><p><strong>Installing Solc</strong></p><p>If you haven’t already, install the Solidity compiler Solc.</p><p><a href="https://solidity.readthedocs.io/en/v0.4.24/installing-solidity.html">Installing the Solidity Compiler - Solidity 0.4.24 documentation</a></p><pre>npm install -g solc</pre><p>Alternatively worth trying Py-Solc which you could use to take your notebooks to the next level. I didn’t for this example, but will in my future projects.</p><p><a href="https://pypi.org/project/py-solc/">https://pypi.org/project/py-solc/</a></p><p><strong>Running local Geth node (optional)</strong></p><p>There is something magic about running your own local node to develop, the best part being able to set a 1sec block time. If you’re an iterative developer like me, short block times definitely help speed everything up.</p><p>I’ll be using a local ethereum node to be testing and deploying to in this example. If you preffer to connect to another chain, you can specify within the notebook, but for now we’ll be installing and running the following script.</p><p><a href="https://ethereum.org/cli">Install the Command Line Tools</a></p><pre>geth --dev --dev.period 2 --datadir ./testchain --rpc --rpccorsdomain ‘*’ --rpcport 8646 --rpcapi “eth,net,web3,debug” --port 32323 --maxpeers 0 console</pre><p><strong>Running Jupyter Notebooks</strong></p><p>Once you have all your dependencies sorted and ready to start, open Jupyter notebooks by running the following.</p><pre>jupyter notebook</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*eH0cMbnxnX1EtgG4p8N-yw.png" /></figure><p>It will open up a file directory for you to navigate to a project folder of your choice and then click the New -&gt;Python 3 Notebook.</p><p>For existing workbooks, simply navigate to their location and open them.</p><h4>Step 2 - Connecting to an Ethereum node</h4><p>For a copy of the files and notebook we’ll be using in this article.</p><p><a href="https://github.com/apguerrera/ethereum-notebooks">apguerrera/ethereum-notebooks</a></p><p>Once you have Jupyter notebooks open, we can start to import some libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*jLg7xA93SoSn38MaQMHruQ.jpeg" /></figure><p>The first three are to let you rerun the cell without error.</p><p>The rest are libraries we’ll be using, including web3.py.</p><p><strong>Connecting to Provider <br></strong>Web3 has a provider type that lets you connect to an Ethereum node or endpoint such as Infura. In our example, we’ll be connecting to a local Geth node running from the /testchain directory, but can be set to any Ethereum node that web3 can connect to.</p><blockquote>w3 = Web3(Web3.IPCProvider(“./testchain/geth.ipc”))</blockquote><p><strong>For Geth users <br></strong>The flowing snippet needs to be included for Geth clients (not Parity). Forgot exactly why but Jupiter doesnt work correctly without it.</p><blockquote>from web3.middleware import geth_poa_middleware<br>w3.middleware_stack.inject(geth_poa_middleware, layer=0)</blockquote><p><strong>Testing calls</strong></p><p>We can call both the blockchain and the user accounts. The cool thing about Jupyter notebooks is that you can easily rerun any cell using shift+enter and the interactive REPL (cell) will show an updated block.number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*LrA-P9dFfwJLjCXEsWo0vg.jpeg" /><figcaption>Displaying the latest block number</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*0dNis7Y1QlH82ycSnfI15Q.jpeg" /><figcaption>Checking accounts using web3.py</figcaption></figure><p>If the accounts dont match with the workbook comments, you’re either connecting to a different node with different accounts, or that the local node hasn’t pulled the account files from the /testchain directory.</p><h4>Step 3- Compiling a Smart Contract using solc</h4><p>So once we have our Jupyter notebook connected and talking to an Ethereum node, the next step is to compile a smart contact and deploy it. Here we’ll use <em>solc</em> to compile a sample solidity file and generate both an ABI and the contract binaries. We’ll use both of those later to deploy it to the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rH69hUOH6IfE1DUP4SYOWA.jpeg" /><figcaption>Sample contract has been compiled with <em>solc and sample ABI displayed</em></figcaption></figure><p>If the contract has multiple files, use a flattener like BokkyPooBah’s Solidity Flattener. Include the following just before the solc step.</p><blockquote>!./solidityFlattener.pl -contractsdir=../contracts -mainsol=WhiteListMain.sol -outputsol=WhiteList.sol</blockquote><h4>Step 4- Sending a signed transaction</h4><p>Once we have a connection to an Ethereum node, we can write a function that would sign* and send a transaction. This will become very useful later as we’ll need to sign a few transactions. Here we let account[0] send all the transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*X_PBlz3F5WpAeQPbzI3tuA.jpeg" /><figcaption>Sample sign_transaction function for development</figcaption></figure><p><em>*Caution! this is a very basic example, only for local testing on a development blockchain with keys holding no monetary value. This would need to be rewritten for signing Main net transactions to protect your keys.</em></p><p>The contracts ABI and binary code are then used to build the contract transaction. We then use our <em>sign_transaction </em>function to broadcast it to the network. A contract address is returned in the receipt. Congratulations, you’ve successfully deployed a smart contract!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD7Ek7FC6u2tsld7prmFCA.png" /><figcaption>Smart contract is successfully deployed with the address shown.</figcaption></figure><h4>Step 5- Interacting with a deployed Smart Contract</h4><p>ConciseContracts is included in the web3.py library and will help reduce the amount of boilerplate needed to send transactions to contracts. Next would be to use the ConciseContracts artefact to start interacting with our deployed contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*-sa4_oWZTohLsGa2-goMIg.jpeg" /></figure><p>Once the contract is instantiated, we can call and sent transactions. In the following example, we send an array of addresses to be added to a whitelist through a signed transaction. In the second cell, we query the smart contract with a call to an <em>isInWhiteList</em> view function, using ConciseContracts to return a boolean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waj0PTE84dSJinF_QLSzfQ.png" /></figure><h4>Using python functions</h4><p>You can also use standard python to script calls and transactions. The example below shows a transaction to another sample token contracts with a <em>mint</em> function. The code below has the first 5 accounts being minted 1000 tokens using a simple python loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*TZ3FrESghj5v-7IPGR4R9A.jpeg" /></figure><p>What you decide to write from here onwards is up to your imagination. Enjoy!</p><h4>Potential Applications</h4><ul><li>Contract UI for semi-technical stakeholders</li><li>Prototyping a series of transactions</li><li>Crowdsale scripting</li><li>Iterative development and deployment</li><li>Smart contract auditing</li></ul><h3>Sample code on Github</h3><p>For sample code, test scripts, solidity flattener and Jupyter notebook used in this example, please visit.</p><p><a href="https://github.com/apguerrera/ethereum-notebooks">apguerrera/ethereum-notebooks</a></p><p>Thanks for reading this far, any feedback and suggestions are welcome!</p><p>- Adrian Guerrera</p><p>telegram: @adrianguerrera<br><a href="http://www.deepyr.com/">www.deepyr.com</a></p><p>Big shout out to <a href="https://twitter.com/BokkyPooBah">BokkyPooBah</a> for his guidance and teachings, from which the workflow and helper functions are heavily inspired by, and to the <a href="https://dffdao.org/">Decentralised Future Fund</a> for all their support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4207afa0085" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepyr/interacting-with-ethereum-using-web3-py-and-jupyter-notebooks-e4207afa0085">Interacting with Ethereum using web3.py and  Jupyter Notebooks</a> was originally published in <a href="https://medium.com/deepyr">Deepyr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing the Dynamic Security Token.]]></title>
            <link>https://medium.com/deepyr/introducing-the-dynamic-security-token-e7a10a72903c?source=rss----d8a321b08114---4</link>
            <guid isPermaLink="false">https://medium.com/p/e7a10a72903c</guid>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[sto]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[erc1400]]></category>
            <dc:creator><![CDATA[Deepyr Tech]]></dc:creator>
            <pubDate>Thu, 14 Feb 2019 05:54:06 GMT</pubDate>
            <atom:updated>2019-02-12T18:05:26.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7A5oV96105QPdQ3zUC7wDw.png" /><figcaption>Traditional securities.</figcaption></figure><h3>Security Tokens</h3><p>Firstly, we’re not talking about those RSA tokens you got from work once... Security Tokens are digital representations of real world assets and securities. They could be stocks or options in a company, and legally they represent and perform the function of traditional securities, but digital. When represented on a smart contract platform like Ethereum, they become programmable, cryptographically secure, and better than traditional securities because of:</p><ul><li>Lower setup costs, issuance and transaction fees for all participants</li><li>Ensure a greater level of security and ownership when on a blockchain.</li><li>Automated legal compliance, regulation and transfer obligations</li><li>Instant settlements &amp; reduced dependency on third party intermediaries.</li><li>Liquidity from regulated trading on decentralised exchanges</li></ul><h3>ERC1400 Security Token Standard.</h3><p>The <a href="https://github.com/ethereum/EIPs/issues/1400">ERC1400 Security Token Standard</a> is the latest development for representing a Security Token on the blockchain from authors Adam Dossa, Fabian Vogelsteller, Stephane Gosselin, and Pablo Ruiz, designed to:</p><blockquote><em>“Accelerate the issuance and management of securities on the Ethereum blockchain by specifying a standard interface through which security tokens can be operated on and interrogated by all relevant parties.”</em></blockquote><p>This comprehensive smart contract standard has been formalised over a series of Ethereum Request for Comments (ERC’s) that make up the ERC1400 Security Token Standard. Namely:</p><blockquote><strong>ERC-1400: Security Token Standard<br></strong>ERC-1410: differentiated ownership / transparent restrictions<br>ERC-1594: on-chain restriction checking with error signalling, off-chain data injection for transfer restrictions and issuance / redemption semantics<br>ERC-1643: document / legend management<br>ERC-1644: controller operations (force transfer)</blockquote><p><em>See also these links:</em><br><a href="https://github.com/ethereum/EIPs/issues/1411">https://github.com/ethereum/EIPs/issues/1411</a><br><a href="https://thesecuritytokenstandard.org/">http://thesecuritytokenstandard.org</a></p><p>Aside from some of the technical specifications above, the ERC1400 Security Token Standard is made up of a clear set of requirements that need to be met in order to be compatible with other ERC1400 Security Tokens and exchanges. We’ll be looking at some of the core components of the Security Token Standard as well as putting some of these pieces together in a new way.</p><h4>Partitions</h4><p>For a security token, partitions are defined as different allocations for the same underlying asset. A great example would be founders shares that have special rules, making them different to the rest of the shares issued. Founders shares could have conditions that convert after 3-4 years. Employees would be in a different partition with a different set of restrictions and converting after, say 1 year. These different share allocations are commonly referred to as classes of shares, tranches or partitions. In the ERC1400 standard, we’ll be referring to these separate types of share as “partitions”.</p><h4>Partition Conversions</h4><p>Since we have a different partitions of the same underlying asset. At a minimum they are partially fungible, we would need them to function as such and/or have a way to convert from one partition to another.</p><h4>Documents</h4><p>Storing documents is also covered in the ERC1400 Security Token standard, and includes features such as storing document pointers, signed and hashed company documents.</p><h4>Whitelisting</h4><p>Aside from regulations affecting token transfers, there are Know Your Customer (AML/KYC) requirements, for say sophisticated investor whitelisting, anti money laundering, different jurisdictions etc. As we get further into security tokens, we also begin to have whitelists for specific partitions.</p><p>Say the company allows for employees to exchange their employee shares privately, among themselves before they are vested. One would need to keep a whitelist for restricting transfers to a list of employees.</p><h4>Token Restrictions</h4><p>Along with having different partitions, tokens will also need to have transfer restrictions for <a href="https://medium.com/lgogroup/understanding-the-regulatory-framework-of-security-tokens-9b231118cab4">a number of reasons</a>. For different asset classes and juristictions, there are rules on the number of investors, total share issuance limits and holding periods. One example would be <a href="https://hackernoon.com/regulation-s-for-stos-310c40948ce">Reg S Category 2&amp;3</a> which has regulations requiring either a 40 day or 12 month resale restrictions.</p><p>Overall security token standards are a great initiative to help improve interoperability for token exchanges, lower settlement time and costs, help standardise regulation and compliance.</p><h3>Cant we keep Tokens, as Tokens!</h3><p>Tokens are great!, But we quickly begin to see as we add more and more functionality to this new security token standard, we also add complexity. Complexity from handling new partitions, different logic for handling new partition conversions, token restrictions and whitelisting requirements, all using immutable smart contracts that cannot be changed once deployed.</p><p>Yet at the same time, securities must adapt throughout the life cycle and events of a real world asset, and so the Security Token contract, must also be dynamic.</p><p>To solve this there are few options, such as creating add-on modules, upgradeable proxy contracts or adding various functionality to the contract. Today I’ll be going through my preferred method, by representing partitions as individual tokens.</p><p>By doing this we’ll open up a composable token architecture which is both flexible and extensible. By keeping tokens as tokens, we’re able to be apply our framework easily to a number of Security Token use-cases, as well as interact with individual partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*VYb1tN77uTT1Q7i3laec4Q.png" /></figure><h4>ERC777</h4><p>The ERC20 token standard was one of the first attempts to create a token standard. It’s our go-to basic token, but not the token standard that will take us where we need to go. One of the more advanced base token contracts now available is the ERC777 token standard, developed by Ethereum developer heavy-weights Jordi Baylina, Jacques Dafflon, and Thomas Shababi.</p><p>We’ll be using standard ERC777 tokens in our design. It’s essentially an advanced, backwards compatible ERC20 with some extra functionality for token operators and uses the ERC820 Registry for safe token transfers (we’ll be using both features later for our token regulator).</p><p><a href="https://medium.com/coinmonks/the-lucky-contract-erc-777-45b53df1454c">https://medium.com/coinmonks/the-lucky-contract-erc-777</a></p><h3>Deepyr’s Dynamic Security Token</h3><p>The Dynamic Security Token is essentially a family of contracts, with a main composeable ERC1400 contract that is able to own multiple tokens.</p><h4>Token Architecture</h4><p>Token Converters are then able to mint and burn, converting one token to another, while regulators contain transfer logic. Together, this family of contracts form the basis of our Dynamic Security Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*82YZyvFbdsF_DZ5Bcuvu1w.png" /><figcaption>Deepyr’s Dynamic Security Token framework</figcaption></figure><p>Each ERC777 token represents a partition, one of which, is the base token. It is this base token that allows standard ERC20 token functions to be handled, while other partitions can be called specifically by partition ID.</p><p>The document / metadata management (ERC-1643) and controller operations (ERC-1644) are also added to the main ERC1400 contract to keep that metadata common all. When included with an ERC820 contract registry for safe token transfers, as well as connecting regulators with whitelist contracts, you begin to have a framework of smart contracts that is both flexible and extensible.</p><p>Well, this might seam overkill for your standard security token (and you’re right!) flexibility and extensibility becomes increasingly important for assets with long life spans, such as your company, with evolving capital requirements, new issuance and changing crypto regulation.</p><p>From a security perspective, this adds granularity that can be utilized when delegating roles based permissions for each contract. DApp developers could also save gas by calling ERC777 token functions directly, instead of traversing through arrays and partition logic, yet still be restricted.</p><h4>Token Regulators</h4><p>To manage token transfers, our approach will be taking advantage of token operator, which comes baked into the ERC777 standard. We’ll also be using the Token Sender and Token Recipient interfaces for our Token Regulators. This lets us add logic on how tokens are able to be sent or received by adding a new regulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*cD4mGpQwf4zFkjdz559mlw.png" /><figcaption>We’ll be using the ERC777 Token restriction contracts as a Token Regulator.</figcaption></figure><h4>Token Converters</h4><p>Each Dynamic Security Token keeps a list of any tokens it manages, as well as a mapping of Token Converters and which tokens they’re able to operate on. Generally the main contract owner has permissions to add or remove token converters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*K2uYYMje5glqXRg7iKQb7Q.png" /><figcaption>Security Contract is able to grant permissions to the Token Converter</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*T6efv04G36nvYY-8t70nig.png" /><figcaption>Token Converter changes Token B into Token A</figcaption></figure><p>When there is new stocks or partitions being issued, that’s simply adding a new ERC777 token into the Dynamic Security Token. This lets your securities scale out by incrementally adding new partitions.</p><p>To convert between partitions, the security contract is able to grant operator permissions to the Token Converter, who then is able to mint Token A and burn Token B, effectively converting a Class B token into a Class A.</p><h4>Extending the Dynamic Security Token</h4><p>Since partitions are just tokens in our architecture, when we deploy a new token contract, any new tokens are added with operator permissions granted to the main contract. We also have the option to add Token Converters or connect partitions to new or existing token regulators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*KXHIiuf02CbHGBYggrW1bw.png" /><figcaption>New partition is added to the Dynamic Security Token</figcaption></figure><p>The main point to highlight here, is that new partitions or class of shares can be added easily and dynamically to an existing Security Token without breaking or redeploying the contract, as well as being able to add logic to define how partitions are converted and exchanged.</p><p>Tokens and converters are immutable smart contracts. The side effect of having separate contracts is having a full audit trail with logs of which token converter address, handled what token, with what contract logic, timestamped when!</p><h3>Token Converter Examples</h3><p>A combination of token converters and token regulators allow for a number of emergent use cases.</p><h4>Internally Traded Employee Share Options</h4><p>For companies wishing to pay a portion of wages in company stock, this would be done by issuing company stock options. Traditionally this involves an accountant, solicitor and an expensive fees, sometimes in the thousands of dollars per employee. In our example, we would be the issuer and able to issue a new partition for the cost of the gas, along with an owner approved token converter and a whitelist including only eligible employees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*99zeIvUwYN8SSIhIceYgtQ.png" /><figcaption>Employee stock options can be added anytime, with rules regulating trading within eligible employees.</figcaption></figure><p>If an employee wishes to trade that option with another employee on the employee whitelist, then the exchange will go ahead.</p><h4>Convertible Stock Options</h4><p>Once they have options, employees could then convert their options into the base security token themselves, using a company approved Token Converter. This token converter could be custom made with a time bound transfer restriction. Say an employee or investor needs to wait 12 months before they can convert their Class X tokens to Class A’s. Initially the transfer will fail, but after a set time, and satisfying any internal logic, the user can then convert these options themselves into Class A shares, all without the intervention or approval of a third party.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*CsS0iDppycY-RZDbRnH7Gw.png" /><figcaption>Tokens are not able to be converted until Feb 2020</figcaption></figure><h4>ERC20 User On boarding</h4><p>Since only the owner can add token converters and set permissions, you could let users migrate your existing ICO token or crowdsale token into a Security Token. By add a different custom Token Converter, like the previous example but an on-ramp, but specifically converts your ERC20’s into Dynamic Security Tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*s4NmNuXnJEGVj8WtqEvhUA.png" /><figcaption>Convert existing ERC20 tokens using a custom Token Converter</figcaption></figure><h3>Dynamic Security Token Extensibility</h3><p>These 4 main components make for a flexible token architecture and at the same time, makes it modular and extensible.</p><h4>Dividend Issuance</h4><p>To issue dividends based on an existing token balance, we can add another custom converter, that will issue dividends based on a balance of Class A’s tokens at the Ex Div date. Check-pointing can be added to the <em>base</em> token, time-stamping each of the token transfers. This allows the smart contract to get the users exact token balance at a certain time, ie. the Ex Div date, and then issue dividends based on token holdings at a certain block.</p><p>Additionally the token converter could potentially hold ETH and distribute dividend payments in ETH as part of the conversion. This makes it really easy for a users to claim their dividends or for a company to push dividends to token holders provided you check pointed appropriately.</p><h4>Token Voting</h4><p>Simply add your governance token to the main Security Contract. New issuance could be handled with a token minter and delegation could be handled with the token regulator. For inspiration, check out the token voting library in <a href="https://github.com/bokkypoobah/ClubEth/blob/master/contracts/ClubEthFactory.sol">BokkyPooBah’s DAO</a></p><h4><strong>Privacy</strong></h4><p>Different industries, jurisdictions and financial vehicles are subject to very strict <a href="https://hackernoon.com/thin-security-token-protocols-a-taxonomy-172c0c6c734b">privacy requirements</a> that need to be addressed in this new world. A series of privacy-protocols based on ideas such as zk-SNARKS, zk-STARKS or BulletProofs are likely to be needed to power a new wave of security tokens. Again, theses are just tokens that can be added or converted to as the technology matures.</p><h4>Upgradeable Security Contracts</h4><p>Components of the framework can be decoupled and replaced as needed, better than most upgradeable design patterns. Deploying a new base security contract will require pointing all the previously attached tokens to the new security contract. Token addresses, balances and history remain the same which is a bonus. Token Converters still know which tokens can be converted. For individual token contracts that need to be upgraded, simply issue a new token, and naturally a token converter would do the job.</p><h4>Debt</h4><p>Once we have a framework for digital assets, naturally we begin to see how debt tokens can be included into our framework. In addition to adding debt tokens, we can start to think of a range of token converter contracts that convert between assets and debts, that can lock up equity as collateral and issue debt tokens, or act as convertible note contracts. The possibilities are endless!</p><h4>Many more..</h4><p>As you can see with this flexible architecture, we keep the standard ERC1400 interface for interoperability and compliance, and at the same time, making it dynamic and extensible. We’re able to be flexible in both how tokens are exchanged with others and converted between partitions, as well as being able to add new partitions, token converters and regulators as needed throughout the life cycle of the asset.</p><p>Next article will hopefully go into a bit more depth into both the regulator and converter contracts, authorisation and permissioning, and hopefully share some code from our upcoming reference implementation.</p><p>Let me know what you think in the comments, or reach out to collaborate!</p><p>Adrian Guerrera<br><a href="https://www.deepyr.com/">www.deepyr.com</a></p><p>This is all inspired by a failed arbitrage attempt on the <a href="https://cryptoderivatives.market/">https://cryptoderivatives.market/</a> where I bought what looked like some cheap MKR tokens, which turned out to be old MKR tokens, and so I had to convert them to new ones. I loved the trustlessness of being able to convert your old tokens into new, and the beauty of interacting with a contract that is immutable and will be available for the life of the network.</p><p>That idea stuck with me when researching then building my own implementation of the ERC1400 standard and naturally fit with the role of Token Converters. I was fortunate enough to participate in the Council of Prague, Security Token ring thanks to the <a href="https://dffdao.org/">DFF</a>, in which the ensuing conversations really cemented the idea, as well as the regular chats on a Friday evening with my mentor BokkyPooBah.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a10a72903c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepyr/introducing-the-dynamic-security-token-e7a10a72903c">Introducing the Dynamic Security Token.</a> was originally published in <a href="https://medium.com/deepyr">Deepyr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>