<?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 John Kohler on Medium]]></title>
        <description><![CDATA[Stories by John Kohler on Medium]]></description>
        <link>https://medium.com/@kohlerjp?source=rss-8105016ca089------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*zMFuLyBw1XHtsnaGwIWVDg.jpeg</url>
            <title>Stories by John Kohler on Medium</title>
            <link>https://medium.com/@kohlerjp?source=rss-8105016ca089------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:24:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kohlerjp/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[How to sign raw Ethereum contract transactions with Elixir]]></title>
            <link>https://kohlerjp.medium.com/how-to-sign-raw-ethereum-contract-transactions-with-elixir-f8822bcc813b?source=rss-8105016ca089------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8822bcc813b</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <dc:creator><![CDATA[John Kohler]]></dc:creator>
            <pubDate>Fri, 18 Jun 2021 12:26:35 GMT</pubDate>
            <atom:updated>2021-06-18T12:26:35.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P3NIwdO40YlLOHU9" /><figcaption>Photo by <a href="https://unsplash.com/@clintadair?utm_source=medium&amp;utm_medium=referral">Clint Adair</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The state of Ethereum libraries for Elixir</h3><p>I’m a huge fan of Elixir and Phoenix, to the point where I could hardly imagine writing a backend web application in anything else. Especially not in Javascript. So when I began experimenting with smart contracts and Ethereum, I was dismayed to see the lack of fleshed out elixir libraries for interacting with the blockchain. Nothing came close to the state-of-the-art Web3.js available for javascript enthusiasts. <a href="https://github.com/hswick/exw3">ExW3</a> was a good candidate, but I found myself forking the repository almost immediately and even needing to fork and update it’s dependencies. Not to mention the nested rust requirements and its <a href="https://elixirforum.com/t/using-rustler-with-otp24/39840">problems with more recent versions of Elixir</a>.</p><p>Furthermore, these libraries did not operate well with Infura. Infura will not store your private keys, so signing raw transactions with these libraries became a stressful hassle of hacking together several frameworks, all of which seemed to come up short. It became so stressful in fact, that I actually gave up on trying to do any of this in Elixir.</p><h3>Add a twist of Python</h3><p>The first part of this tutorial may come as a surprise, in that we’re not actually going to use Elixir to build and sign transactions. The libraries sadly just aren’t there yet (as of June 2021). Instead we’re going to use python and the <a href="https://web3py.readthedocs.io/en/stable/">web3.py</a> library to talk to the blockchain, but we’re going to facilitate this conversation through our Elixir application with the help of the <a href="http://erlport.org/">:erlport</a> dependency. Essentially, we will start up python in an Elixir process, and send messages to trigger our python functions.</p><p>Let’s start out by creating a python file called contracts.py. We’ll also need to make sure we have the web3.py library installed, which can be done with pip.</p><p>pip install web3</p><p>Assuming you have a local blockchain running through a service such as Ganache, we can begin to setup our web3 python module. I’m using a previously deployed contract, and have included the private key as an environment variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e086e0a59058e8e9e6b0c2f908d7fe4/href">https://medium.com/media/1e086e0a59058e8e9e6b0c2f908d7fe4/href</a></iframe><p>Sending the raw transaction will return a hex value, but we’ll want to send a string back to our elixir process, which can be done by calling .hex(). I’ve named this file contracts.py and I’ve placed it in a priv/python/ directory.</p><p>Now we just need to call this function from our Elixir app. The first step is adding the :erlport dependency, allowing us to talk to python.</p><pre>defp deps do<br> [{:erlport, &quot;~&gt; 0.10.1&quot;}]<br>end</pre><p>Next we need a module which will create the python processes and talk to our blockchain functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a922d0d64dbd86bd8971dda2a4f6ca30/href">https://medium.com/media/a922d0d64dbd86bd8971dda2a4f6ca30/href</a></iframe><p>We start the python process with python.start, giving it the python module directory and the version of python we want to run. Next, python.call sends a function call to the process, accepting the process_id, python module name, function name, and function arguments respectively. We then stop the process when we are done with it.</p><p>If you’ve run this code, you might encounter an error when trying to call PythonContract.call_hello(&quot;name&quot;).</p><pre>Could not identify the intended function with name &#39;sayHello&#39;, positional argument(s) of type &#39;(&lt;class \&#39;bytes\&#39;&gt;)</pre><p>This is because python will accept the string argument as a binary, we’ll need to convert it to an ascii string before using it as such.</p><pre>name_string = name.decode(&#39;ascii&#39;)</pre><p>Voila! We are able to talk to the blockchain through python in our Elixir application.</p><p>I discovered this process while working on Nifty Media, a platform that makes it easier than ever for content creators to mint and share NFTs with their top followers.</p><p>Follow us on twitter for more updates! <a href="https://twitter.com/nifty_media">@nifty_media</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8822bcc813b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using While Loops in Elixir]]></title>
            <link>https://kohlerjp.medium.com/using-while-loops-in-elixir-efc368149aa1?source=rss-8105016ca089------2</link>
            <guid isPermaLink="false">https://medium.com/p/efc368149aa1</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[while-loop]]></category>
            <dc:creator><![CDATA[John Kohler]]></dc:creator>
            <pubDate>Sat, 04 May 2019 15:12:41 GMT</pubDate>
            <atom:updated>2020-06-10T15:38:22.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lBQAXo51K46oX33_" /><figcaption>Photo by <a href="https://unsplash.com/@harshaldesai?utm_source=medium&amp;utm_medium=referral">Harshal Desai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Most people would tell you not to use a while loop in Elixir. And most people are right. Since <a href="https://codingwithalchemy.com/stateless-in-seattle-how-elixir-creates-state/">data is immutable</a>, they generally won’t do you much good. But I am not most people.</p><p>A common while loop looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb4d4a016ee32f6b031c0c5ab61e3f0/href">https://medium.com/media/fcb4d4a016ee32f6b031c0c5ab61e3f0/href</a></iframe><p>This wouldn’t quite work in Elixir. The value of x can&#39;t change, so depending on the value of x, the loop would either continue forever, or finish immediately. Not so helpful is it? &quot;But Wait!&quot; you proudly shout, &quot;We can just reassign the value of x and loop to our hearts content&quot;. But thats not <em>really</em> a loop in the traditional sense. Using a reassigned variable would be the equivalent of calling a function recursively, which incidentally, is how you &quot;loop&quot; in Elixir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8833dc5418d02d466da5c074e5242f7/href">https://medium.com/media/a8833dc5418d02d466da5c074e5242f7/href</a></iframe><p>And voilà, you have iterative code. Since true while loops require mutable data, it&#39;s understandable why they weren&#39;t included in the language. But I&#39;ve always been a rebel at heart. Who is José Valim to tell me what I can and can&#39;t do? While loops are my God given right!</p><h3>Dealing with State</h3><p>Here’s the hard truth. State happens. To prove it, I’ve written a stoplight server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e032e6adaf3d765e3fa96a04db67b2f5/href">https://medium.com/media/e032e6adaf3d765e3fa96a04db67b2f5/href</a></iframe><p>This is a simple GenServer that updates it’s internal traffic light state every millisecond (I’m told this is how it works in Los Angeles). We’re also given a check_light function to view the state at any time. Now, if I want to consume this information, I&#39;ll need to interact with a stateful world. I&#39;ve also written a bit of self driving car software that interacts with the stoplight server. Like Elon, I&#39;ve decided to open source my code for an autonomous vehicle. You&#39;re welcome mankind.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a764708fa423f41ab8e020404ab2f62/href">https://medium.com/media/9a764708fa423f41ab8e020404ab2f62/href</a></iframe><p>This will repeatedly check the stoplight to see if it’s green. If it is not green, it will tell you to wait (yes, even on yellow lights you freewheelin’ maniac). Simple stuff. The kind of stuff that seems perfect for a while loop, so I’m going to use one. Let’s try writing us an old fashioned while function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/226b8f9dbc333656fdaeee1fca059b28/href">https://medium.com/media/226b8f9dbc333656fdaeee1fca059b28/href</a></iframe><p>We created a function that will check a given value, and if true, will perform the given function recursively until that value isn’t true anymore.</p><p>But running this against our stateful server will highlight a problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cfe78da16d07ed7a4bceefef164466e/href">https://medium.com/media/7cfe78da16d07ed7a4bceefef164466e/href</a></iframe><p>Our loop will either continue forever, or finish immediately. The stateful expression is computed before being passed into the function. The check_light function is only called once on the initial while invocation. If we want to re-evaluate the predicate on every iteration, we&#39;ll have to wrap it inside yet another function. But I think we&#39;re starting to stray too far from the while loop I want. Lets crank the volume up to 11 and utilize some macros.</p><h3>A Macro While</h3><p>Now most people will tell you not to use macros unless <strong>absolutely</strong> necessary. And I’m going to have to agree with most people here. But this is absolutely necessary, nothing gets between me and my while loops. Here’s while written as a macro.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d23e823cb9e76161255754e8ee55d02/href">https://medium.com/media/8d23e823cb9e76161255754e8ee55d02/href</a></iframe><p>This does some pretty gnarly stuff. We define an anonymous recursive function, which accepts a function that will be called if the predicate evaluates to true. After defining this function, we pass it into itself. This is just a trick to create a recursive function while avoiding the def keyword, allowing us to call our while outside of a module definition.</p><p>Despite all this ugliness, we actually get a pretty slick interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e89b5ac5a7fb3272f6e5d9abebb6775/href">https://medium.com/media/5e89b5ac5a7fb3272f6e5d9abebb6775/href</a></iframe><p>This is almost perfect, but the syntax isn’t quite right. While.while? This ain’t the <a href="https://www.youtube.com/watch?v=_zXKtfKnfT8">while while west</a>. I just want a plain and simple, no frills while loop. I also want the title of this post to be clever, so we&#39;re going to use the __using__ keyword. When a module uses use with another module, it will immediately call the __using__ callback from the module being used. We&#39;re going to use this to define a macro in the Car module. Have I used the word &quot;use&quot; enough in this paragraph? I need the SEO points.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3511ebea722c4c915af5105e46eef43/href">https://medium.com/media/c3511ebea722c4c915af5105e46eef43/href</a></iframe><p>And there you have it! When the Car module is compiled, it will call the __using__ macro, which defines it&#39;s own while macro inside of Car. And now we can call while straight from our Car module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d98899c1dd4c42654bdff658578974c/href">https://medium.com/media/9d98899c1dd4c42654bdff658578974c/href</a></iframe><h3>Closing Thoughts</h3><p>Even after all this, we’re still using recursion. We just gave it an unnecessary paint job. You don’t need while loops. Use recursion, it&#39;s cleaner and more fun.</p><p><em>Originally published at </em><a href="https://codingwithalchemy.com/using-while-loops-in-elixir/"><em>https://codingwithalchemy.com</em></a><em> on May 4, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc368149aa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateless in Seattle: How Elixir Creates State]]></title>
            <link>https://kohlerjp.medium.com/stateless-in-seattle-how-elixir-creates-state-df1d5a87bb23?source=rss-8105016ca089------2</link>
            <guid isPermaLink="false">https://medium.com/p/df1d5a87bb23</guid>
            <category><![CDATA[immutable]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elixir]]></category>
            <dc:creator><![CDATA[John Kohler]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 20:57:21 GMT</pubDate>
            <atom:updated>2019-04-28T13:37:19.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PN5WnMm5ajeuIccgJoXJA.jpeg" /></figure><h3>Data is Immutable</h3><p>Data structures in Elixir are immutable. Once I define a value, it cannot be changed. When I declare the list of outer planets as</p><pre>outer_planets = [&quot;Jupiter&quot;, &quot;Saturn&quot;, &quot;Neptune&quot;, &quot;Pluto&quot;]</pre><p>There’s not a damn thing I, nor Neil Degrasse Tyson could do to remove “Pluto” from that list. Sure, I could try to change it, but all attempts will create a <em>new</em> list, leaving the old one fully intact.</p><pre>iex&gt; outer_planets = [&quot;Jupiter&quot;, &quot;Saturn&quot;, &quot;Neptune&quot;, &quot;Pluto&quot;]`, <br>iex&gt; updated_planets = List.delete(outer_planets, &quot;Pluto&quot;)<br>iex&gt; IO.inspect(updated_planets)<br>iex&gt; [&quot;Jupiter&quot;, &quot;Saturn&quot;, &quot;Neptune&quot;]<br>iex&gt; IO.inspect(outer_planets)<br>iex&gt; [&quot;Jupiter&quot;, &quot;Saturn&quot;, &quot;Neptune&quot;, &quot;Pluto&quot;]</pre><p>Although nothing stops me from simply re-assigning the variable to a different, non-mutable list to reflect my preference for the Greek Gods.</p><pre>outer_planets = [&quot;Zeus&quot;, &quot;Cronus&quot;, &quot;Poseidon&quot;, &quot;Hades&quot;]</pre><p>This is a detail that tripped me up a bit when I was first starting in Elixir. I would consider functional languages like Haskell or ML, where once an identifier was assigned, there was no going back. At first glance, this looks a hell of a lot like a mutation.</p><p>The key is that the <em>actual</em> list is not changing at all. The list of the planets with Roman names (Jupiter, Saturn, Neptune, Pluto) still exists unchanged, we just don’t have a name for it anymore. The list did not <em>change</em>, we created an entirely new list (Zeus, Cronus, …) and decided to call it outer_planets instead of the list of Roman gods.</p><p>So cool, Elixir has immutable data. This is great for a whole bunch of reasons. None of which I’ll get into now.</p><h3>Elixir is not Stateless</h3><p>Sure, you can’t mutate data, but it’d be unfair to say Elixir is entirely stateless. A language needs to interact with the outside world, otherwise, programs would just make your computer hot. Lets imagine we wanted to build a very simple server. All this server would do is keep count. We could tell the server to increment the count, or we could request the current count. Easy. Lets do this by writing a recursive function called count:</p><pre>def count(message, count) do<br>  cond do<br>    message == :increment -&gt; count(message, count + 1)<br>    message == :get -&gt; count<br>  end<br>end</pre><p>Uh oh, this doesn’t really work. Calling count(:increment, 0) will loop forever, and calling count(:get, 0) will just return 0. We don&#39;t have a way to get the state of count out of the function. To do this, we&#39;ll have to take advantage of Elixir processes.</p><h3>Introducing — Elixir Processes</h3><p>Elixir processes are somewhat similar to system processes. They run on the erlang VM and are incredibly lightweight. The Elixir docs boast that even modest systems can run hundreds of thousands of these processes concurrently without breaking a sweat. Processes have two important properties that we’ll need for our stateful count server. First, a new process can be created by using the spawn function.</p><pre>process_id = spawn(fn -&gt; 1 + 1 end)</pre><p>spawn accepts a function, and will return the process id of a new process. This new process performs the given function and exits. We&#39;ll need this process id later on.</p><p>Processes also have the ability to send and receive messages to/from each other. They essentially have a ‘mailbox’, which we will be spamming with all our state, keeping our code immutable and clean.</p><p>A process can send a message to a given process id, or it can call receive to look at the first message in it&#39;s mailbox. Calling receive when no messages are in the mailbox will cause the process to wait until a message is found (of course timeouts and configurations can be made, this is just the default behavior). Here&#39;s an example:</p><pre>def print_message() do <br>  receive do <br>    message -&gt; IO.inspect(message) <br>  end <br>end </pre><pre>process_id = spawn(print_message)<br>send(process_id, &quot;Some message&quot;)</pre><p>Lets break down what happened here.</p><ol><li>We define a function that will wait to receive a message in it’s mailbox and then print it out. receive has a body similar to case, the clause matching the received message is computed.</li><li>We spawn a process that runs this function. The process will immediately get to the receive do, and then wait until it receives any message.</li><li>We send a message to that process. The message identifier will match, and the message get&#39;s printed.</li></ol><p>Now that we have all these pieces in place, we can finally finish our counting server, sell it to Google and become millionaires. Lets use our recursive count function from before, but this time we will use process message passing to send and receive information regarding the illusive count.</p><pre>def count(current_count) do<br>  receive do<br>    :increment -&gt;<br>      count(current_count + 1)<br>    {:get, pid} -&gt; <br>      send(pid, current_count)<br>      count(current_count)<br>  end<br>end</pre><pre>process_id = spawn(fn -&gt; count(0) end)<br>send(process_id, :increment)<br>send(process_id, :increment)<br>send(process_id, :increment)<br>send(process_id, :increment)<br>send(process_id, {:get, self()}) # self is the current process id</pre><p>We’ve built a process that runs an infinitely looping recursive function, which responds to our requests to alter or receive data. But when we run the above code, we don’t get an answer back. Did our response get lost in the mail?</p><p>Well no, we just never checked our mailbox. We’ll have to call receive in the current process to actually look at the response.</p><pre>receive do<br>  response -&gt; IO.puts(response)<br>end</pre><p>There you go! We built a stateful server using immutable data. Of course, this would be a huge pain in the ass to implement every time we needed to utilize state. Luckily, Elixir provides wrappers around these interfaces in the form of Agents and GenServers, which we will explore in later posts.</p><p><em>Originally published at </em><a href="https://codingwithalchemy.com/stateless-in-seattle-how-elixir-creates-state/"><em>https://codingwithalchemy.com</em></a><em> on April 27, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df1d5a87bb23" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>