<?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 Evan Diewald on Medium]]></title>
        <description><![CDATA[Stories by Evan Diewald on Medium]]></description>
        <link>https://medium.com/@evandiewald?source=rss-1faf67ba837e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gqHbPeCNrrM96gLvF40ZJw.jpeg</url>
            <title>Stories by Evan Diewald on Medium</title>
            <link>https://medium.com/@evandiewald?source=rss-1faf67ba837e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:45:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@evandiewald/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[Solving Github Issues with AI Agents]]></title>
            <link>https://medium.com/data-science-collective/solving-github-issues-with-ai-agents-da63221e4761?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/da63221e4761</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 19:51:56 GMT</pubDate>
            <atom:updated>2025-03-03T19:51:56.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lOy3dpCSWszuVcPj" /><figcaption>Photo by <a href="https://unsplash.com/@ballonandon?utm_source=medium&amp;utm_medium=referral">Ben Allan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of the natural “first frontiers” of Generative AI has been in its applications to the software development lifecycle (SDLC). Due to the troves of valuable training data from publicly-available sources like Github and Stack Overflow, LLM’s have become quite adept at generating, debugging, and analyzing code.</p><p>Tools like <a href="https://github.com/features/copilot?ef_id=_k_CjwKCAiAt4C-BhBcEiwA8Kp0CX-nLcMkuWp-hwgXUhoa8qdJ9hvffLREj3bIJX6uIEFsFHxD9nNpghoCWTAQAvD_BwE_k_&amp;OCID=AIDcmmb150vbv1_SEM__k_CjwKCAiAt4C-BhBcEiwA8Kp0CX-nLcMkuWp-hwgXUhoa8qdJ9hvffLREj3bIJX6uIEFsFHxD9nNpghoCWTAQAvD_BwE_k_&amp;gad_source=1&amp;gclid=CjwKCAiAt4C-BhBcEiwA8Kp0CX-nLcMkuWp-hwgXUhoa8qdJ9hvffLREj3bIJX6uIEFsFHxD9nNpghoCWTAQAvD_BwE">Github Copilot</a> and the <a href="https://www.cursor.com/en">Cursor</a> have enjoyed broad adoption by developers, who use them to automate many aspects of software creation &amp; maintenance.</p><p>However, real-world software engineering tasks, such as diagnosing and resolving bugs in large-scale codebases, still present challenges for LLM’s:</p><ol><li>Though context windows are getting larger, <strong>you generally cannot capture an entire repository’s content within an input prompt.</strong> We need efficient ways to search and navigate code.</li><li><strong>LLM’s interface with code differently than humans </strong>— we have to consider this nuance when designing secure &amp; effective tools for AI Agents. The need for an “Agent-Computer Interface” (ACI) is discussed extensively in the <a href="https://arxiv.org/pdf/2405.15793">SWE-Agent</a> paper.</li><li><strong>Generative models are probabilistic in nature and can come up with unexpected results</strong>. It is important to leverage this penchant for creative solutions while keeping the agent on track.</li></ol><p>This real-world complexity demonstrates the value of benchmarks like <a href="https://www.swebench.com/">SWE-Bench</a>, which tasks LLM’s and workflows with solving Github issues in popular open-source repositories like matplotlib, pytest, and django.</p><p>SWE-Bench not only provides a dataset, but a robust framework for automated test evaluation. Submissions are assessed based on whether or not they solve unit tests that validate the fix.</p><p>I see this benchmark as a relatively approachable opportunity to get hands-on with bleeding-edge concepts in the field, like agentic orchestration and test-time compute. The SWE-Bench <a href="https://www.swebench.com/">leaderboard</a> is constantly evolving, not just due to the release of more powerful foundation models, but also as teams experiment with more effective workflows.</p><p><strong>In this article, I’ll discuss my solution, called </strong><a href="https://github.com/evandiewald/aegis"><strong>Aegis</strong></a><strong>, which at the time of writing, achieves a resolution rate of 33.67% on SWE-Bench Lite, surpassing submissions from large organizations like Amazon and IBM.</strong></p><blockquote>Why Aegis?</blockquote><blockquote>The <strong>aegis</strong> (<a href="https://en.wikipedia.org/wiki/Help:IPA/English">/ˈiːdʒɪs/</a> <a href="https://en.wikipedia.org/wiki/Help:Pronunciation_respelling_key"><em>EE-jis</em></a>;<a href="https://en.wikipedia.org/wiki/Aegis#cite_note-1">[1]</a> <a href="https://en.wikipedia.org/wiki/Ancient_Greek_language">Ancient Greek</a>: αἰγίς <em>aigís</em>), as stated in the <a href="https://en.wikipedia.org/wiki/Iliad"><em>Iliad</em></a>, is a device carried by <a href="https://en.wikipedia.org/wiki/Athena">Athena</a> and <a href="https://en.wikipedia.org/wiki/Zeus">Zeus</a>, variously interpreted as an animal skin or a <a href="https://en.wikipedia.org/wiki/Shield">shield</a> and sometimes featuring the head of a <a href="https://en.wikipedia.org/wiki/Gorgon">Gorgon</a>.</blockquote><blockquote>The modern concept of doing something “under someone’s <em>aegis</em>” means doing something under the protection of a powerful, knowledgeable, or benevolent source.</blockquote><blockquote>-Wikipedia</blockquote><p>aegis was also a cheat code in <a href="https://ageofempires.fandom.com/wiki/Cheat_code_(Age_of_Empires_II)">Age of Empires II</a> allowing for instantaneous building and resource gathering.</p><p><strong>Just want to see the code?</strong> Check out the <a href="https://github.com/evandiewald/aegis">Aegis repository on Github</a> (and feel free to leave a ⭐️).</p><h4>The “Agent-Computer Interface” &amp; Environment Setup</h4><p>In my view, the environment setup is the most complicated aspect of the solution. Because each repository (and issue) has its own state of files and dependencies, the agent runs commands interactively within a Docker container. This sandboxed environment also ensures that a rogue agent cannot do much damage on my broader system.</p><p>Fortunately, the SWE-Bench team provides Docker images for each issue instance, but I had to create a layer over these environments to execute pre-defined commands safely. The <a href="https://github.com/evandiewald/aegis/blob/main/issue_reviewer/environment.py">Environment</a> class provides this abstraction (and some useful methods, like execute_command, ls, and get_patch ) atop the Docker client.</p><p>Next, the <a href="https://github.com/evandiewald/aegis/blob/main/issue_reviewer/editor.py">Editor</a> class provides a more model-friendly abstraction over the Environment, i.e. our Agent-Computer Interface. This is the heart of the solution, and defines the tools for file viewing, editing, searching, and test execution.</p><p>Let’s examine the file viewing tools as an example.</p><p>When the LLM uses the open_file tool, it must provide a file_path and line_number. If the path/line are both valid, we return an interactive “window” to the LLM, e.g. for open_file(django/db/models/fields/related.py, 860), the tool returns:</p><pre>Opened file: django/db/models/fields/related.py<br>...854 lines above...<br>855:         ] if self.unique else []<br>856: <br>857:     def deconstruct(self):<br>858:         name, path, args, kwargs = super().deconstruct()<br>859:         del kwargs[&#39;to_fields&#39;]<br>860:         del kwargs[&#39;from_fields&#39;]<br>861:         # Handle the simpler arguments<br>862:         if self.db_index:<br>863:             del kwargs[&#39;db_index&#39;]<br>864:         else:<br>865:             kwargs[&#39;db_index&#39;] = False<br>866:         if self.db_constraint is not True:<br>867:             kwargs[&#39;db_constraint&#39;] = self.db_constraint<br>868:         # Rel needs more work.<br>869:         to_meta = getattr(self.remote_field.model, &quot;_meta&quot;, None)<br>870:         if self.remote_field.field_name and (<br>871:                 not to_meta or (to_meta.pk and self.remote_field.field_name != to_meta.pk.name)):<br>872:             kwargs[&#39;to_field&#39;] = self.remote_field.field_name<br>873:         return name, path, args, kwargs<br>874: <br>875:     def to_python(self, value):<br>876:         return self.target_field.to_python(value)<br>877: <br>878:     @property<br>879:     def target_field(self):<br>880:         return self.foreign_related_fields[0]<br>881: <br>882:     def get_reverse_path_info(self, filtered_relation=None):<br>883:         &quot;&quot;&quot;Get path from the related model to this field&#39;s model.&quot;&quot;&quot;<br>884:         opts = self.model._meta<br>885:         from_opts = self.remote_field.model._meta<br>886:         return [PathInfo(<br>887:             from_opts=from_opts,<br>888:             to_opts=opts,<br>889:             target_fields=(opts.pk,),<br>890:             join_field=self.remote_field,<br>891:             m2m=not self.unique,<br>892:             direct=False,<br>893:             filtered_relation=filtered_relation,<br>894:         )]<br>...</pre><p>The window starts a few lines before the provided line number. You can see the view includes some annotations on top of the actual file contents, e.g. line numbers and the Opened file: header. These components are subtle, but help provide the LLM with useful context for further search &amp; editing.</p><p>From here, the model also has tools for scroll_up and scroll_down , which require no arguments because we track the “currently open” file. These simply paginate the window up or down.</p><p>We’ll discuss &amp; demo more of the other tools as we dive into the workflow itself.</p><h4>General Workflow</h4><p>At a high level, the Aegis agentic workflow is designed to mimic the approach that human developers might take:</p><ol><li>Task Understanding &amp; Planning</li><li>Fault Localization</li><li>Editing Code</li><li>Validation</li><li>Iterate if Necessary</li></ol><blockquote>While most solutions, including my own, focus on <strong>Agentic </strong>workflows — meaning the LLM “Agent” has a meaningful degree of flexibility in what actions it takes, there is an excellent and efficient submission called “Agentless” which uses a linear action path. I learned a lot from the <a href="https://arxiv.org/abs/2407.01489">Agentless paper</a> and <a href="https://github.com/OpenAutoCoder/Agentless">codebase</a> as I was architecting Aegis.</blockquote><p>For agentic orchestration, I’m using <a href="https://www.langchain.com/langgraph">LangGraph</a> &amp; <a href="https://www.langchain.com/">LangChain</a> to simplify some of the undifferentiated heavy lifting around parsing and tool configuration, while maintaining sufficient customization. This helped me bootstrap the <a href="https://github.com/evandiewald/aegis/blob/main/issue_reviewer/agent.py">workflow</a> relatively quickly.</p><p>Let’s break down each of these steps and some of the most common ideas.</p><h4><strong>Task Understanding &amp; Planning</strong></h4><p>A typical bug report might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6XSdm9tdJN2QVB4AZvwnA.png" /><figcaption>One of the SWE-Bench test instances from the astropy repository.</figcaption></figure><p>There’s often a description of the issue, expected behavior, and steps to reproduce. This gives maintainers a relatively clear starting point for how to replicate the bug and evaluate a potential fix.</p><p>Agent-based solutions almost always start with a “planning” phase. With the recent excitement of “deep reasoning” models like OpenAI’s o1 or DeepSeek R1, this long-form thinking phase is baked into the model’s behavior during post-training.</p><p>However, it’s important to note that most LLM’s can be coaxed to demonstrate some level of <a href="https://arxiv.org/pdf/2201.11903">chain-of-thought</a> behavior, whether through few-shot prompting or by simply stating “<a href="https://arxiv.org/pdf/2205.11916">Let’s think step by step</a>”.</p><p>Either way, this understanding/planning step is crucial for breaking down complex tasks. Here is an example plan that Aegis generated for an issue in the Django repository:</p><pre>Let me understand the issue being reported:<br><br>1. There&#39;s a bug in Django&#39;s `SQLCompiler.get_order_by()` method where it&#39;s incorrectly removing an &quot;order by\&quot; clause created as a multiline `RawSQL`.<br>2. The issue happens because the `ordering_parts.search(sql)` is searching through multiline SQL, but only returning the last line containing \&quot;ASC\&quot; or \&quot;DESC\&quot; words.<br>3. These last lines are added to a `seen` set, and if multiple raw queries have identical last lines, only the first clause is returned from `SQLCompiler.get_order_by()`.<br>4. The reporter suggests fixing this by joining the SQL string with spaces to make it a single line before applying the regex search: `sql_oneline = &#39; &#39;.join(sql.split(&#39;\\n&#39;))`.<br><br>Let me first locate the relevant code in the codebase to understand the issue better.<br>I should look for `SQLCompiler.get_order_by()` method which should be in the Django ORM code.</pre><h4>Fault Localization</h4><p>This is arguably the most important phase with the widest range of possible approaches and complexity. Think about how a human developer might comb through a new codebase. They’d browse the file tree, scan files, and possibly search for references of specific functions or classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7lu3yjkA9FNoVlvUX3Q7Q.png" /><figcaption>Github’s UI is carefully crafted to support efficient browsing of large repo’s.</figcaption></figure><p>Humans are very efficient when it comes to scanning a large amount of context and selectively forgetting the 95% that is not relevant. In contrast, transformer-based LLM’s are near-perfect memorizers of relatively small amounts of data.</p><p>For my implementation, I wanted to give the agent flexibility in terms of the search modality, but constrain it in important ways. There are 2 main “search” tools in Aegis:</p><ul><li>grep-style explicit/keyword search</li><li>Semantic search based on vector embeddings of code snippets</li></ul><p>For semantic search, I split code chunks based on the syntax tree to distinguish classes and functions rather than naively chunking based on character count. I also categorize this “code index” into source code vs test code to provide another meaningful filter.</p><p>As a preprocessing step, snippets are encoded using Cohere Embed v3 and stored in a local FAISS vectorstore. This approach was significantly inspired by the fantastic <a href="https://github.com/aorwall/moatless-tools/blob/main/moatless/index/code_index.py">Moatless Tools</a> codebase.</p><p>When the semantic_search tool is invoked given a natural language query and optional filters, the top 10 most semantically-similar code blocks are first sent to a lightweight LLM (Haiku 3.5) to “re-rank” and identify the most relevant segments, which are returned to the main thread. This cuts down on the number of tokens used in the core conversation while ensuring useful context is still captured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*3gge7CNtOQ4JXsPo5dQg1A.png" /><figcaption>Truncated example of the semantic_search tool output, which contains code blocks relevant to the query.</figcaption></figure><p>If the agent knows precisely what keywords it is looking for, it may opt to use the more direct explicit_search tool. This returns up to 100 instances of the search term by file and line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YwBdROxeczAN3ej-4l7JCA.png" /><figcaption>The explicit_search tool is useful for directly searching for specific keywords.</figcaption></figure><p>Another effective variation is to start by asking the agent to attempt to replicate the issue, as the resulting traceback will generally offer a great starting point for debugging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_kd1UXFEveorq31zjprtA.png" /></figure><p>I experimented with this approach, and while it often works well, I found that in certain settings, the agent gets bogged down attempting to configure the test environment rather than directly addressing the issue. As is a general theme with agentic workflows, there is a balancing act between structure and flexibility.</p><h4>Editing Code</h4><p>Once the agent has identified which files &amp; functions are the source of the issue, it moves on to the editing phase.</p><p>Creating effective tools for LLM’s to edit files proved to be a challenge in itself. Originally, my edit tool was inspired by the <a href="https://arxiv.org/pdf/2405.15793">SWE-Agent paper</a>. The arguments were a file path, a start and end line, and replacement text that would replace the file contents at that range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoIyroXnv2QRTNXzCS9uiA.png" /><figcaption>File editing based on line numbers proved to be too complex for the initial agent.</figcaption></figure><p>This turned out to be extremely error prone. The model would often cutoff too few or too many lines or disregarded indentation. Even as a human I find this tool to be a bit cumbersome.</p><p>Like in the SWE-Agent paper, I was able to slightly improve performance by adding an automated linting step (e.g. flake8) immediately after the edit was attempted — if the linting failed, it would give the LLM another try.</p><p>However, even with the linting step, edits still failed far too often. Further, it violated one of the design principles I had in mind from the start — I want to avoid functionality that has to be configured for each individual programming language. Java will have a different linter than Python, with its own nuanced configuration and installation steps.</p><p>The file editing toolset that I ultimately settled on comes from <a href="https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/computer_use_demo/tools/edit.py?ref=musings.yasyf.com">Anthropic</a>. They found that the <a href="https://www.anthropic.com/research/swe-bench-sonnet">most effective edit tool</a> for LLM’s is a simple str_replace which replaces old_str with new_str. This avoids the clunkiness of specifying line ranges and lets the model be more direct in its intentions. I find that the str_replace tool rarely fails, and I was able to remove the complexity of the linter as a result.</p><p>In cases where the agent needs to add a net new line (e.g. to add an import statement or new test case), the insert tool accepts a line number and new_text that will be inserted at that line.</p><h4>Validation</h4><p>Once edits have been made, the agent needs to verify 1) that the changes will not break existing tests and then 2) that they actually resolve the original bug.</p><p>Again, I took inspiration here from <a href="https://github.com/aorwall/moatless-tools/blob/main/moatless/index/code_index.py#L508">Moatless Tools</a>. When a file is edited, Aegis automatically runs relevant test cases and returns the results within the edit response. How do we identify relevant test files? We use the most semantically-similar test file path.</p><p>For example, if the agent edits django/utils/decorators.py, we run tests from tests/utils_tests/test_decorators.py. You can see an example response from the str_replace tool below. At the bottom is the test summary, where any failures would be surfaced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MmK1VtCLklETJ9gA8B5IjA.png" /><figcaption>Code editing with automated test execution.</figcaption></figure><p>By automatically running tests after edits, we eliminate a decision point of having the model determine the test file and execute it explicitly. It shows whether or not the agent broke existing code and guides it where to go next.</p><p>The model is also encouraged (but not required) to create its own test case(s) specific to the issue at hand. The most confident predictions from the agent are those that have been properly validated.</p><h4>Iterate if Necessary</h4><p>The strength of agentic workflows comes from their ability to take nonlinear solution paths. After making edits, Aegis will sometimes realize that it needs to gather additional context, e.g. look at alternative implementations beyond what was mentioned in the original issue. After all, bug reports often come from unexpected edge cases, and we do not want the fix to break the function’s typical use.</p><h4>A Note on Test-Time Compute</h4><p>A lot of the best-performing instances on SWE-Bench leverage some sort of <a href="https://arxiv.org/html/2408.03314v1">inference-time scaling</a>. This is a fascinating area of research in its own right, and at a high level, the idea is that while much of the effort around improving LLM performance has been focused on scaling <em>training </em>capacity (e.g. larger models, more sophisticated fine-tuning strategies), you can also consider scaling <em>inference </em>capacity.</p><p>One simple way to scale inference is to have the model generate N solutions in parallel, then submit the modal outcome, or even have a separate set of AI entities “vote” on the best solution. More complex approaches around <a href="https://arxiv.org/pdf/2410.20285">Monte Carlo Tree Search</a> balance depth and breadth of different decision paths using a separate reward model.</p><p>In my resource-constrained setting, I have not yet explored such strategies within Aegis. However, I will be closely watching this space and thinking about efficient implementations, e.g. using a central “supervisor” agent based on a powerful reasoning model that can guide a “swarm” of cheaper task-oriented models. To take this to an extreme case, OpenAI recently turned heads by showing <a href="https://arcprize.org/blog/oai-o3-pub-breakthrough">breakthrough results on ARC-AGI</a> at a cost of over $3000 per task!</p><h4>Example Trajectory</h4><p>You can glean a lot about the model’s behavior and limitations by watching example <strong><em>trajectories</em></strong>, or chain-of-thought threads as the agent works through a problem.</p><p>Let’s review the trajectory for the Aegis run with Claude 3.7 Sonnet for instance id scikit-learn__scikit-learn-15512, which corresponds to the following bug report:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_6rwdW_2qj4P0y88_pvew.png" /></figure><p><strong>Task Understanding &amp; Planning</strong></p><p>The agent starts by breaking down the problem and the expected behavior. It comes up with a step-by-step plan to confirm and then fix the bug.</p><blockquote><strong>Aegis Output:</strong></blockquote><blockquote>The documentation for the Affinity Propagation algorithm in scikit-learn states that when the algorithm doesn’t converge:<br>1. `cluster_center_indices_` should return an empty array<br>2. `labels_` should return -1 for each sample</blockquote><blockquote>However, the user reports that when the algorithm doesn’t converge (by setting a very low `max_iter` value), they get:<br>1. `cluster_center_indices_` returns `[2]` (not an empty array)<br>2. `labels_` returns `[0, 0, 0]` (not `-1` for each sample)</blockquote><blockquote>The user mentions they’re using scikit-learn version 0.20.3.</blockquote><blockquote>So the task is to:<br>1. Confirm if this is a bug<br>2. Fix the behavior so it matches the documentation or update the documentation if the behavior is intended</blockquote><blockquote>Let me start by searching for the Affinity Propagation implementation in scikit-learn.</blockquote><p><strong>Fault Localization</strong></p><p>Next, Aegis uses the provided search tools to start gathering relevant context and identify the source of the convergence issue.</p><p>It uses the semantic_search tool with the query affinity_propagation function implementation . This successfully retrieves the relevant code block, shown below (output is truncated):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ko3hdJOAa-NKzw8Yv_xXKQ.png" /></figure><p>Aegis decides to narrow in on the relevant convergence check in affinity_propagation — we can see the output of the open_file tool below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2bSiZWNMMe2q9Fu2vG3vQ.png" /></figure><p>Great! Aegis has identified the flaw and has an action plan:</p><blockquote><strong>Aegis Output:</strong></blockquote><blockquote>Now I understand the issue. Here’s what’s happening:</blockquote><blockquote>1. Looking at line 196: `if (not unconverged and (K &gt; 0)) or (it == max_iter):`, the algorithm breaks out of the loop when either:<br> — The algorithm converges (`not unconverged and (K &gt; 0)`)<br> — OR when it reaches the maximum number of iterations (`it == max_iter`)</blockquote><blockquote>2. When `max_iter` is reached, it still identifies exemplars in the current state at line 204 and proceeds with clustering, regardless of whether convergence was achieved.</blockquote><blockquote>3. There’s no flag being set to identify whether convergence was actually reached.</blockquote><blockquote>4. Lines 222–226 only set the “not converged” result (`labels = np.array([-1] * n_samples)` and `cluster_centers_indices = []`) if there are no exemplars (`K == 0`), not if the algorithm hasn’t converged.</blockquote><blockquote>This is why when the algorithm doesn’t converge (because max_iter is too small), but still has identified some exemplars, it returns those exemplars instead of the “not converged” result.</blockquote><blockquote>Let me fix this issue by modifying the code to properly track convergence status:</blockquote><p><strong>Code Editing &amp; Validation</strong></p><p>Aegis now uses the str_replace tool to make the appropriate edits, including a new converged flag and updates to the return logic to ensure it aligns with expectations. Relevant existing tests are automatically run, and they all pass! This means that the change likely did not break anything in an unexpected way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbYMK4Eyl2JQcffOMiBpSw.png" /></figure><p>Though this would technically address the expected behavior, the agent recognizes that the reporter also requested a new property (e.g. converged_ in order to track this flag. Here we get an interesting example of Aegis handling its own mistakes — it first tries to blindly update the AffinityPropagation class, but it doesn’t have the existing code exactly right, so the str_replace tool returns an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-xxm9uHv3t6efLUMUXAyg.png" /></figure><p>Aegis uses the open_file command to revisit the exact snippet, then revises its edit. This time, it succeeds. It also recognizes that we should add this new property to the docstring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MG0pifnzi2LtX8-1lzHdHg.png" /></figure><p>The agent next plans to add an additional test case to test_affinity_propagation.py to further validate the new changes, but at this point execution stops due to a configured recursion limit that I set in order to keep costs &amp; latency manageable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-a_xvbYrMJwJlBj7YVgEAA.png" /></figure><p>This provided patch resolves the issue successfully, based on the SWE-Bench test harness.</p><h4>Results &amp; Observations</h4><p>At this time, I’ve experimented with Claude 3.5 Sonnet v2, OpenAI o3-mini, and the brand-new <a href="https://www.anthropic.com/news/claude-3-7-sonnet">Claude 3.7 Sonnet</a> with “hybrid reasoning” capabilities. I use SWE-Bench Lite (a smaller, more cost-effective subset of 300 instances from the full SWE-Bench dataset) for validation.</p><p>My run with 3.5 Sonnet was under 30% accuracy on SWE-Bench Lite when I stopped execution, and Aegis with o3-mini finished with a resolution rate of 30.67%. <strong>The run with 3.7 Sonnet showed the best performance, with a resolution rate of 33.67% (101 / 300 resolved instances)</strong>. While far from the top of the <a href="https://www.swebench.com/index.html#lite">leaderboard</a>, I was encouraged by this result, which surpassed submissions by large organizations like Amazon and IBM.</p><p>Some observations:</p><ul><li>As is noted by the providers themselves, <strong>pure deep reasoning models like o1 have </strong><a href="https://platform.openai.com/docs/guides/reasoning"><strong>different prompting strategies</strong></a> compared to general purpose (GPT-class) LLM’s. Reasoning models are purpose-built for complex tasks like SWE-Bench, so I look forward to following the research (and coming up with my own ideas) for the most effective ways to utilize this new type of model.</li><li><strong>The performance jump from 3.5 Sonnet to 3.7 is stark</strong>. 3.7 seems to do a better job gathering relevant context in advance, which keeps it from getting caught in “local minima”, i.e. dead-end decision paths. However, I am noticing that it sometimes takes <em>too long</em> to start making edits, and the model hits a self-imposed 25-step limit.</li><li><strong>Token efficiency is an area where I can absolutely improve</strong>. My conversation threads get quite long, affecting cost and latency significantly. I’m planning to look into ways to decompose tasks and/or truncate/summarize previous steps without losing important context.</li></ul><p>As a final note —</p><p>Building agentic workflows involves solving a hundred tiny decisions, both in terms of conventional software development and this probabilistic, often unintuitive world of working with LLM’s whose capabilities are constantly evolving.</p><p><strong>This space is accelerating so quickly because of open-source contributions, publications, and competitive benchmarks like SWE-Bench.</strong> It has been fascinating to follow the growing body of research and hands-on demonstrations!</p><p><a href="https://github.com/evandiewald/aegis">https://github.com/evandiewald/aegis</a></p><h4>References</h4><ul><li><a href="https://arxiv.org/abs/2310.06770">SWE-Bench</a></li><li><a href="https://github.com/aorwall/moatless-tools">Moatless Tools</a></li><li><a href="https://github.com/OpenAutoCoder/Agentless">Agentless</a></li><li><a href="https://arxiv.org/pdf/2405.15793">SWE-Agent</a></li><li><a href="https://www.anthropic.com/research/swe-bench-sonnet">Anthropic Blog: Raising the bar on SWE-bench Verified with Claude 3.5 Sonnet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da63221e4761" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-collective/solving-github-issues-with-ai-agents-da63221e4761">Solving Github Issues with AI Agents</a> was originally published in <a href="https://medium.com/data-science-collective">Data Science Collective</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Fantasy Football Research Agent with LangGraph]]></title>
            <link>https://medium.com/data-science/building-a-fantasy-football-research-agent-with-langgraph-ad8deb0126f1?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad8deb0126f1</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[fantasy-football]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 19:01:39 GMT</pubDate>
            <atom:updated>2025-01-12T22:43:45.905Z</atom:updated>
            <content:encoded><![CDATA[<h4>An end-to-end guide covering integration with the Sleeper API, creation of a Streamlit UI, and deployment via AWS CDK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXwl0LlaKrjmL4nJ" /><figcaption>Photo by <a href="https://unsplash.com/@fotograw?utm_source=medium&amp;utm_medium=referral">Dmitriy Demidov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s embarrassing how much time I spend thinking about my fantasy football team.</p><p>Managing a squad means processing a firehose of information — injury reports, expert projections, upcoming bye weeks, and favorable matchups. And it’s not just the volume of data, but the ephemerality— if your star RB tweaks a hamstring during Wednesday practice, you better not be basing lineup decisions off of Tuesday’s report.</p><p>This is why general-purpose chatbots like Anthropic’s Claude and OpenAI’s ChatGPT are essentially useless for fantasy football recommendations, as they are limited to a static training corpus that cuts off months, even years ago.</p><p>For instance, if we ask Claude Sonnet 3.5 who the current best running back is, we see names like Christian McCaffrey, Breece Hall, and Travis Etienne, who have had injury-ridden or otherwise disappointing seasons thus far in 2024. There is no mention of Saquon Barkley or Derrick Henry, the obvious frontrunners at this stage. (Though to Claude’s credit, it discloses its limitations.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*Gh9y3w3hSE8kkn2WNuKmOw.png" /></figure><p>Apps like <a href="https://www.perplexity.ai/">Perplexity</a> are more accurate because they do access a search engine with up-to-date information. However, it of course has no knowledge of my entire roster situation, the state of our league’s playoff picture, or the nuances of our keeper rules.</p><p>There is an opportunity to tailor a fantasy football-focused <strong>Agent </strong>with tools and personalized context for each user.</p><p>Let’s dig into the implementation.</p><h4>Architecture Overview</h4><p>The heart of the chatbot will be a <a href="https://www.langchain.com/langgraph">LangGraph</a> Agent based on the <a href="https://arxiv.org/abs/2210.03629">ReAct</a> framework. We’ll give it access to tools that integrate with the <a href="https://docs.sleeper.com/">Sleeper API</a> for common operations like checking the league standings, rosters, player stats, expert analysis, and more.</p><p>In addition to the LangGraph API server, our backend will include a small Postgres database and Redis cache, which are used to manage state and route requests. We’ll use <a href="https://streamlit.io/">Streamlit</a> for a simple, but effective UI.</p><p>For development, we can run all of these components locally via <a href="https://docs.docker.com/compose/">Docker Compose</a>, but I’ll also show the infrastructure-as-code (IaC) to deploy a scalable stack with <a href="https://docs.aws.amazon.com/cdk/api/v2/">AWS CDK</a>.</p><h4>Sleeper API Integration</h4><p><a href="https://sleeper.com/">Sleeper</a> graciously exposes a public, read-only API that we can tap into for user &amp; league details, including a full list of players, rosters, and draft information. Though it’s not documented explicitly, I also found some GraphQL endpoints that provide critical statistics, projections, and — perhaps most valuable of all — recent expert analysis by NFL reporters.</p><p>I created a simple API client to access the various methods, which you can find <a href="https://github.com/evandiewald/fantasy-football-agent/blob/main/fantasy_chatbot/sleeper.py">here</a>. The one trick that I wanted to highlight is the requests-cache <a href="https://requests-cache.readthedocs.io/en/stable/index.html">library</a>. I don’t want to be a greedy client of Sleeper’s freely-available datasets, so I cache responses in a local Sqlite database with a basic TTL mechanism.</p><p>Not only does this lessen the amount redundant API traffic bombarding Sleeper’s servers (reducing the chance that they blacklist my IP address), but it significantly reduces latency for my clients, making for a better UX.</p><p>Setting up and using the cache is dead simple, as you can see in this snippet —</p><pre>import requests_cache<br>from urllib.parse import urljoin<br>from typing import Union, Optional<br>from pathlib import Path<br><br><br>class SleeperClient:<br>    def __init__(self, cache_path: str = &#39;../.cache&#39;):<br><br>        # config<br>        self.cache_path = cache_path<br>        self.session = requests_cache.CachedSession(<br>            Path(cache_path) / &#39;api_cache&#39;, <br>            backend=&#39;sqlite&#39;,<br>            expire_after=60 * 60 * 24,<br>        )<br><br>        ...<br><br>    def _get_json(self, path: str, base_url: Optional[str] = None) -&gt; dict:<br>        url = urljoin(base_url or self.base_url, path)<br>        return self.session.get(url).json()<br><br>    def get_player_stats(self, player_id: Union[str, int], season: Optional[int] = None, group_by_week: bool = False):<br>        return self._get_json(<br>            f&#39;stats/nfl/player/{player_id}?season_type=regular&amp;season={season or self.nfl_state[&quot;season&quot;]}{&quot;&amp;grouping=week&quot; if group_by_week else &quot;&quot;}&#39;,<br>            base_url=self.stats_url,<br>        )</pre><p>So running something like</p><p>self.session.get(url)</p><p>first checks the local Sqlite cache for an unexpired response that particular request. If it’s found, we can skip the API call and just read from the database.</p><h4>Defining the Tools</h4><p>I want to turn the Sleeper API client into a handful of key functions that the Agent can use to inform its responses. Because these functions will effectively be invoked by the LLM, I find it important to annotate them clearly and ask for simple, flexible arguments.</p><p>For example, Sleeper’s API’s generally ask for numeric player id’s, which makes sense for a programmatic interface. However, I want to abstract that concept away from the LLM and just have it input player names for these functions. To ensure some additional flexibility and allow for things like typos, I implemented a basic “<a href="https://github.com/rapidfuzz/RapidFuzz">fuzzy search</a>” method to map player name searches to their associated player id.</p><pre># file: fantasy_chatbot/league.py<br><br>def get_player_id_fuzzy_search(self, player_name: str) -&gt; tuple[str, str]:<br>  # will need a simple search engine to go from player name to player id without needing exact matches. returns the player_id and matched player name as a tuple<br>  nearest_name = process.extract(query=player_name, choices=self.player_names, scorer=fuzz.WRatio, limit=1)[0]<br>  return self.player_name_to_id[nearest_name[0]], self.player_names[nearest_name[2]]<br><br># example usage in a tool<br>def get_player_news(self, player_name: Annotated[str, &quot;The player&#39;s name.&quot;]) -&gt; str:<br>    &quot;&quot;&quot;<br>    Get recent news about a player for the most up-to-date analysis and injury status.<br>    Use this whenever naming a player in a potential deal, as you should always have the right context for a recommendation.<br>    If sources are provided, include markdown-based link(s)<br>    (e.g. [Rotoballer](https://www.rotoballer.com/player-news/saquon-barkley-has-historic-night-sunday/1502955) )<br>    at the bottom of your response to provide proper attribution<br>    and allow the user to learn more.<br>    &quot;&quot;&quot;<br>    player_id, player_name = self.get_player_id_fuzzy_search(player_name)<br>    # news<br>    news = self.client.get_player_news(player_id, limit=3)<br>    player_news = f&quot;Recent News about {player_name}\n\n&quot;<br>    for n in news:<br>        player_news += f&quot;**{n[&#39;metadata&#39;][&#39;title&#39;]}**\n{n[&#39;metadata&#39;][&#39;description&#39;]}&quot;<br>        if analysis := n[&#39;metadata&#39;].get(&#39;analysis&#39;):<br>            player_news += f&quot;\n\nAnalysis:\n{analysis}&quot;<br>        if url := n[&#39;metadata&#39;].get(&#39;url&#39;):<br>            # markdown link to source<br>            player_news += f&quot;\n[{n[&#39;source&#39;].capitalize()}]({url})\n\n&quot;<br><br>   return player_news</pre><p>This is better than a simple map of name to player id because it allows for misspellings and other typos, e.g. saquon → Saquon Barkley</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*X8IWaGUOARHnmS5CUnGQ4w.png" /></figure><p>I created a number of useful tools based on these principles:</p><ul><li>Get League Status (standings, current week, no. playoff teams, etc.)</li><li>Get Roster for Team Owner</li><li>Get Player News (up-to-date articles / analysis about the player)</li><li>Get Player Stats (weekly points scored this season with matchups)</li><li>Get Player Current Owner (critical for proposing trades)</li><li>Get Best Available at Position (the waiver wire)</li><li>Get Player Rankings (performance so far, broken down by position)</li></ul><p>You can probably think of a few more functions that would be useful to add, like details about recent transactions, league head-to-heads, and draft information.</p><h4>LangGraph Agent</h4><p>The impetus for this entire project was an opportunity to learn the LangGraph ecosystem, which may be becoming the de facto standard for constructing agentic workflows.</p><p>I’ve hacked together agents from scratch in the past, and I wish I had known about LangGraph at the time. It’s not just a thin wrapper around the various LLM providers, it provides immense utility for building, deploying, &amp; monitoring complex workflows. I’d encourage you to check out the <a href="https://academy.langchain.com/courses/intro-to-langgraph">Introduction to LangGraph</a> course by LangChain Academy if you’re interested in diving deeper.</p><p>As mentioned before, the graph itself is based on the ReAct framework, which is a popular and effective way to get LLM’s to interact with external tools like those defined above.</p><p>I’ve also added a node to persist long-term memories about each user, so that information can be persisted across sessions. I want our agent to “remember” things like users’ concerns, preferences, and previously-recommended trades, as this is not a feature that is implemented particularly well in the chatbots I’ve seen. In graph form, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*ZzlpGPazE96e54VDG3mEdw.png" /></figure><p>Pretty simple right? Again, you can checkout the full graph definition in the <a href="https://github.com/evandiewald/fantasy-football-agent/blob/main/fantasy_chatbot/chatbot.py">code</a>, but I’ll highlight the write_memory node, which is responsible for writing &amp; updating a profile for each user. This allows us to track key interactions while being efficient about token use.</p><pre>def write_memory(state: MessagesState, config: RunnableConfig, store: BaseStore):<br>    &quot;&quot;&quot;Reflect on the chat history and save a memory to the store.&quot;&quot;&quot;<br><br>    # get the username from the config<br>    username = config[&quot;configurable&quot;][&quot;username&quot;]<br><br>    # retrieve existing memory if available<br>    namespace = (&quot;memory&quot;, username)<br>    existing_memory = store.get(namespace, &quot;user_memory&quot;)<br><br>    # format the memories for the instruction<br>    if existing_memory and existing_memory.value:<br>        memory_dict = existing_memory.value<br>        formatted_memory = (<br>            f&quot;Team Name: {memory_dict.get(&#39;team_name&#39;, &#39;Unknown&#39;)}\n&quot;<br>            f&quot;Current Concerns: {memory_dict.get(&#39;current_concerns&#39;, &#39;Unknown&#39;)}&quot;<br>            f&quot;Other Details: {memory_dict.get(&#39;other_details&#39;, &#39;Unknown&#39;)}&quot;<br>        )<br>    else:<br>        formatted_memory = None<br><br>    system_msg = CREATE_MEMORY_INSTRUCTION.format(memory=formatted_memory)<br><br>    # invoke the model to produce structured output that matches the schema<br>    new_memory = llm_with_structure.invoke([SystemMessage(content=system_msg)] + state[&#39;messages&#39;])<br><br>    # overwrite the existing user profile<br>    key = &quot;user_memory&quot;<br>    store.put(namespace, key, new_memory)</pre><p>These memories are surfaced in the <a href="https://github.com/evandiewald/fantasy-football-agent/blob/main/fantasy_chatbot/prompts.py">system prompt</a>, where I also gave the LLM basic details about our league and how I want it to handle common user requests.</p><h4>Streamlit UI and Demo</h4><p>I’m not a frontend developer, so the UI leans heavily on Streamlit’s components and familiar chatbot patterns. Users input their Sleeper username, which is used to lookup their available leagues and persist memories across threads.</p><p>I also added a couple of bells and whistles, like implementing token streaming so that users get instant feedback from the LLM. The other important piece is a “research pane”, which surfaces the results of the Agent’s tool calls so that user can inspect the raw data that informs each response.</p><p>Here’s a quick demo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkjdgbJ14EQE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkjdgbJ14EQE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkjdgbJ14EQE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4076e5f39771c68327b58492407ecff0/href">https://medium.com/media/4076e5f39771c68327b58492407ecff0/href</a></iframe><h4>Deployment</h4><p>For development, I recommend deploying the components locally via the provided docker-compose.yml file. This will expose the API locally at http://localhost:8123 , so you can rapidly test changes and connect to it from a local Streamlit app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*FNzcdUCzn2wLWZ0MFLZexQ.png" /></figure><p>I have also included IaC for an AWS CDK-based deployment that I use to host the app on the internet. Most of the resources are defined <a href="https://github.com/evandiewald/fantasy-football-agent/blob/main/deploy/lib/fantasy-football-agent-stack.ts">here</a>. Notice the parallels between the docker-compose.yml and the CDK code related to the ECS setup:</p><p>Snippet from docker-compose.yml for the LangGraph API container:</p><pre># from docker-compose.yml<br><br>langgraph-api:<br>    image: &quot;fantasy-chatbot&quot;<br>    ports:<br>        - &quot;8123:8000&quot;<br>    healthcheck:<br>        test: curl --request GET --url http://localhost:8000/ok<br>        timeout: 1s<br>        retries: 5<br>        interval: 5s<br>    depends_on:<br>        langgraph-redis:<br>            condition: service_healthy<br>        langgraph-postgres:<br>            condition: service_healthy<br>    env_file: &quot;../.env&quot;<br>    environment:<br>        REDIS_URI: redis://langgraph-redis:6379<br>        POSTGRES_URI: postgres://postgres:postgres@langgraph-postgres:5432/postgres?sslmode=disable// file: fantasy-football-agent-stack.ts</pre><p>And here is the analogous setup in the CDK stack:</p><pre>// fantasy-football-agent-stack.ts<br><br>const apiImageAsset = new DockerImageAsset(this, &#39;apiImageAsset&#39;, {<br>  directory: path.join(__dirname, &#39;../../fantasy_chatbot&#39;),<br>  file: &#39;api.Dockerfile&#39;,<br>  platform: assets.Platform.LINUX_AMD64,<br>});<br>const apiContainer = taskDefinition.addContainer(&#39;langgraph-api&#39;, {<br>  containerName: &#39;langgraph-api&#39;,<br>  image: ecs.ContainerImage.fromDockerImageAsset(apiImageAsset),<br>  portMappings: [{<br>    containerPort: 8000,<br>  }],<br>  environment: {<br>    ...dotenvMap,<br>    REDIS_URI: &#39;redis://127.0.0.1:6379&#39;,<br>    POSTGRES_URI: &#39;postgres://postgres:postgres@127.0.0.1:5432/postgres?sslmode=disable&#39;<br>  },<br>  logging: ecs.LogDrivers.awsLogs({<br>    streamPrefix: &#39;langgraph-api&#39;,<br>  }),<br>});<br><br>apiContainer.addContainerDependencies(<br>  {<br>    container: redisContainer,<br>    condition: ecs.ContainerDependencyCondition.HEALTHY,<br>  },<br>  {<br>    container: postgresContainer,<br>    condition: ecs.ContainerDependencyCondition.HEALTHY,<br>  },<br>)</pre><p>Aside from some subtle differences, it’s effectively a 1:1 translation, which is always something I look for when comparing local environments to “prod” deployments. The DockerImageAsset is a particularly useful resource, as it handles building and deploying (to ECR) the Docker image during synthesis.</p><blockquote><strong>Note: </strong>Deploying the stack to your AWS account via npm run cdk deploy WILL incur charges. In this demo code I have not included any password protection on the Streamlit app, meaning anyone who has the URL can use the chatbot! I highly recommend adding some additional security if you plan to deploy it yourself.</blockquote><h4>Takeaways</h4><p><strong>You want to keep your tools simple</strong>. This app does a lot, but is still missing some key functionality, and it will start to break down if I simply add more tools. In the future, I want to break up the graph into task-specific sub-components, e.g. a “News Analyst” Agent and a “Statistician” Agent.</p><p><strong>Traceability and debugging are more important with Agent-based apps than traditional software</strong>. Despite significant advancements in models’ ability to produce structured outputs, LLM-based function calling is still inherently less reliable than conventional programs. I used LangSmith extensively for debugging.</p><p><strong>In an age of commoditized language models, there is no replacement for reliable reporters.</strong> We’re at a point where you can put together a reasonable chatbot in a weekend, so how do products differentiate themselves and build moats? This app (or any other like it) would be useless without access to high-quality reporting from analysts and experts. In other words, the Ian Rapaport’s and Matthew Berry’s of the world are more valuable than ever.</p><h4>Repo</h4><p><a href="https://github.com/evandiewald/fantasy-football-agent/tree/main">GitHub - evandiewald/fantasy-football-agent</a></p><p><em>All images, unless otherwise noted, are by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad8deb0126f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-a-fantasy-football-research-agent-with-langgraph-ad8deb0126f1">Building a Fantasy Football Research Agent with LangGraph</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Planning the Perfect Hike with NetworkX and OpenStreetMap]]></title>
            <link>https://medium.com/data-science/planning-the-perfect-hike-with-networkx-and-openstreetmap-2fbeaded3cc6?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbeaded3cc6</guid>
            <category><![CDATA[route-optimization]]></category>
            <category><![CDATA[openstreetmap]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[geospatial]]></category>
            <category><![CDATA[hiking]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Wed, 31 Aug 2022 01:31:12 GMT</pubDate>
            <atom:updated>2022-08-31T05:19:02.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YP9EYRJYNKFsxBnV8gyLrg.jpeg" /><figcaption>View from Trail Rider Pass in the Snowmass Wilderness, Colorado, USA (image by author).</figcaption></figure><h4>How to build an open-source hike-planning app and route optimization engine</h4><p>Any avid hiker will tell you that the key to a good experience on the trail is adequate preparation. Should I pack rain gear? How long will I have to walk between water sources? What is the best shelter for the terrain and season?</p><p>The most important question is also the simplest — where am I going to go?</p><p>Guidebooks provide useful information about the key attractions in a particular park or region, but the details can be outdated or difficult to adapt to your preferences. Apps like <a href="https://www.alltrails.com/">AllTrails</a> have revolutionized hike planning by crowdsourcing popular routes, photos, and reviews. However, many of their “Premium” features, like the ability to print maps or download them for offline use, require a paid subscription. Further, by distilling a complex trail system into a few curated hikes, I often feel limited by the options listed in AllTrails’ search results.</p><p>Thus, I set out to build my own open-source hike-planning app and route optimization engine that supplement the functionality of proprietary sites. In this article, I’ll walk through (pun intended) the independent components of the system and show how they come together in a demo. Just want to see the code? Check out the repository <a href="https://github.com/evandiewald/trail-mapping">here</a>.</p><h4>Data Sources</h4><p>When it comes to free datasets for route planning, <a href="https://www.openstreetmap.org/">OpenStreetMap</a> is the clear choice. In fact, even <a href="https://support.alltrails.com/hc/en-us/articles/360019246411-OSM-Derivative-Database-Derivation-Methodology">AllTrails</a> adapts their global trail database from OSM’s <a href="https://wiki.openstreetmap.org/wiki/Overpass_API">Overpass API</a>, filtering for only the walkable way segments.</p><p>One of the pain points of working with geospatial data is that it comes in a wide range of file formats, each with their own strengths and weaknesses. In this project, I used different data structures for storage, visualization, and analysis of the trail maps.</p><p>For the route planning task, a graph-based representation makes sense; trails, like roads, are made up of nodes (intersections) and edges (path segments). This allows us to leverage graph algorithms like <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Djikstra’s algorithm</a> in our route optimization function.</p><p>My strategy for this particular component of the app is nothing new, as there is already a broad ecosystem of <a href="https://shakasom.medium.com/routing-street-networks-find-your-way-with-python-9ba498147342">tutorials and libraries</a> dedicated to graph-based way planning. Tools like <a href="https://osmnx.readthedocs.io/en/stable/">OSMnx</a> provide a high-level interface to query the OSM dataset by geocode (e.g. “Shenandoah National Park, Virginia, USA”) and convert the response into <a href="https://networkx.org/">NetworkX</a> graphs. Below is the load_map function that I use to download trail data and save the geometric information in graph- (for efficient computation) and GeoJSON-based (visualization) formats.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec735d4b5209c3900af2b83bf24bc14/href">https://medium.com/media/3ec735d4b5209c3900af2b83bf24bc14/href</a></iframe><p>However, a unique aspect of planning hiking routes is that in addition to latitude and longitude, <em>elevation </em>is a critical third dimension to the design space. Like any good trail map, our tool should be keenly aware of topographic features.</p><p>My custom elevation API uses high resolution radar data collected in 2000 by the Space Shuttle <em>Endeavor. </em>For about 18GB of hard drive space, the <a href="https://portal.opentopography.org/raster?opentopoID=OTSRTM.042013.4326.1">SRTM GL3</a> dataset covers nearly 120M square kilometers of Earth’s landmass in 90m increments. Using the <a href="https://rasterio.readthedocs.io/en/latest/index.html">rasterio</a> library, we can extract elevation profiles from path segments without loading the full map into memory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2e0847f2730bbf58121240420e5be75/href">https://medium.com/media/a2e0847f2730bbf58121240420e5be75/href</a></iframe><p>Not bad, right? It is interesting to note that <a href="https://developers.google.com/maps/documentation/elevation/usage-and-billing">Google currently charges $5 per 1000 requests to their Elevation API</a>, but thanks to NASA and a few lines of code, we can get the same high-quality results, free of charge.</p><h4>Application and UI</h4><p><a href="https://dash.plotly.com/introduction">Dash</a> is my preferred framework for building interactive dashboards in Python. By abstracting the frontend into customizable components, it allows data scientists to focus on the functionality of their use case, rather than design. Since there are already dozens of excellent Dash tutorials and examples, I’ll focus on the layout and logic of my specific application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBnEciXYRN2aYyYHh53r0g.png" /></figure><p>As you might expect, the UI is focused on the map, which utilizes Mapbox’s <a href="https://www.mapbox.com/maps/outdoors">topographic</a> tileset. A dropdown allows you to select from cached trail systems, or you can download new ones by geocode.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771f537315a12fe3fa0e1527a4f099fb/href">https://medium.com/media/771f537315a12fe3fa0e1527a4f099fb/href</a></iframe><p>Once a region is selected, the OSM trail network is visualized using the <a href="https://dash-leaflet.herokuapp.com/">dash-leaflet</a> library. As your planned route materializes on the 2-dimensional map (more on this in the next section), the accompanying elevation profile is plotted in real-time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elGWKRksKGfw9QC7MEGGuw.png" /><figcaption>Viewing all 3 dimensions of a loop around Old Rag Mtn. in Shenandoah National Park (image by author).</figcaption></figure><h4>Route Planning Engine</h4><p>My app allows the user to plan their hike using one of two “modes”. In “Custom” mode, you simply click on intersections around the map and see your route come to life, one segment at a time. Behind the scenes, we try to intelligently connect points using a shortest path algorithm. In the following animation, we see a user-defined route taking shape in Cuyahoga National Park.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjsvC7Vhj2dyRjwAIidZYQ.gif" /><figcaption>Clicking through a route in Cuyahoga National Park (image by author).</figcaption></figure><p>The auto mode is a bit more interesting. My goal here was to create a constrained optimization function that considers the main factors I’d look for when planning a loop:</p><ul><li>Elevation gain</li><li>Distance</li><li>Traversing as much unique trail as possible (i.e. minimize the amount of backtracking on the same paths at multiple points in the hike)</li></ul><p>Mathematically, the optimal loop will satisfy the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*rkUNAe2ZjKm0I_CO.png" /></figure><p>Where <em>P </em>is the path, <em>d(P) </em>is the path distance, <em>D </em>is the target distance,<em> r(P) </em>is the fraction of traversed nodes that are unique (e.g. an out-and-back would have an r-value of 0.5), <em>e(P) </em>is the elevation gain of the path, and<em> E </em>is the target elevation gain.</p><p>Traversing a cyclic graph to find available loops is also a non-trivial task. In the end, I opted for an approach that combines <a href="https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html#networkx.algorithms.shortest_paths.generic.shortest_path">shortest paths</a> and <a href="https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.cycles.simple_cycles.html#networkx.algorithms.cycles.simple_cycles">simple cycles</a>, which are paths that do not contain any repeat nodes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fd556f6fd12cb63614ddf231197037f/href">https://medium.com/media/7fd556f6fd12cb63614ddf231197037f/href</a></iframe><p>Clicking the map near a trail intersection defines the root node for the find_best_loop function, i.e. the terminus of the loop. This enables users to automatically generate hikes that start and end at a key location, like a parking lot or trailhead. Below, the algorithm suggests a rigorous trek over <a href="https://www.nps.gov/places/old-rag.htm">Old Rag Mountain</a> in Shenandoah National Park to meet the supplied constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kL9RxLFlusWpZEasTe8Vwg.gif" /><figcaption>Using the route optimization engine and user-defined constraints to automatically generate the perfect loop (image by author).</figcaption></figure><p>An interesting aside about calculating cumulative elevation gain — surprisingly, there is no clear mathematical definition. You can imagine that if you included every segment with a positive slope, even relatively flat, but bumpy paths could result in significant elevation changes. The key is to smooth the curves by adding a <a href="https://github.com/evandiewald/trail-mapping/blob/c0255e3c7766e211b099a399735dcc812af72702/mapping_utils.py#L101">rolling threshold</a> (a user-defined hyperparameter), as described in this <a href="https://www.gpsvisualizer.com/tutorials/elevation_gain.html">article</a>.</p><h4>Exporting Routes to Navigation Tools</h4><p>Once you’ve planned the perfect hike, you’ll want to export it as an orienteering-friendly format. For a hard copy version, the map and elevation profile can be printed directly from the UI.</p><p>However, users can also export their routes as GPX files (yet another geospatial format) and upload them to AllTrails, Gaia, Google Maps, and other GPS tracking applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jx9szPJYYO60eLeskWd2vQ.gif" /><figcaption>Exporting the route as a GPX file and uploading it to AllTrails (image by author).</figcaption></figure><p>Now, you can navigate your custom route from your phone, just like any other curated AllTrails hike!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*a7gOgej7Ih2Y5gJnMaCelQ.png" /><figcaption>Leveraging AllTrails’ mobile app to track my custom hike (image by author).</figcaption></figure><h4>Wrapping Up</h4><p>In this demo, we leveraged open-source geographic datasets from OSM and NASA to build a functional hike planning application. Using a combination of graph theory, numerical analysis, and domain expertise, we came up with a mathematically-sound route optimization engine to automatically find complete loops that meet individual goals.</p><p>I’m looking forward to continuously improving the UI and underlying algorithms. If you’d like to run the code for yourself, see the full repository on <a href="https://github.com/evandiewald/trail-mapping">Github</a>.</p><h4>References</h4><p>Aric A. Hagberg, Daniel A. Schult and Pieter J. Swart, <a href="http://conference.scipy.org/proceedings/SciPy2008/paper_2/">“Exploring network structure, dynamics, and function using NetworkX”</a>, in <a href="http://conference.scipy.org/proceedings/SciPy2008/index.html">Proceedings of the 7th Python in Science Conference (SciPy2008)</a>, Gäel Varoquaux, Travis Vaught, and Jarrod Millman (Eds), (Pasadena, CA USA), pp. 11–15, Aug 2008</p><p>Map data copyrighted OpenStreetMap contributors and available from <a href="https://www.openstreetmap.org/">https://www.openstreetmap.org</a></p><p>NASA Shuttle Radar Topography Mission (SRTM)(2013). Shuttle Radar Topography Mission (SRTM) Global. Distributed by OpenTopography. <a href="https://doi.org/10.5069/G9445JDF.">https://doi.org/10.5069/G9445JDF.</a> Accessed: 2022–08–30</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbeaded3cc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/planning-the-perfect-hike-with-networkx-and-openstreetmap-2fbeaded3cc6">Planning the Perfect Hike with NetworkX and OpenStreetMap</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Helium Network with Graph Theory]]></title>
            <link>https://medium.com/data-science/exploring-the-helium-network-with-graph-theory-66cbb8bffff9?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/66cbb8bffff9</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[helium]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 17:06:24 GMT</pubDate>
            <atom:updated>2021-10-06T17:06:24.559Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using blockchain data to extract insights about network coverage and “suspicious” hotspots</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lnGO64eHxyO-vdlh" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Quick Primer on the Helium Network</h4><p>This article is going to assume that you have some basic familiarity with the <a href="https://www.helium.com/">Helium Blockchain</a> and specifically, its purpose-built work algorithm called <a href="https://docs.helium.com/blockchain/proof-of-coverage">Proof of Coverage</a>. Essentially, each wireless radio in the network periodically broadcasts “beacons”, which are just small packets of encrypted data. Any hotspot that “witnesses” (receives) this transmission reports it to the blockchain in a receipt. This constant communication between nearby hotspots helps prove that adequate coverage is provided in a given geographic region, and miners are rewarded for providing this service in an honest way. I’d encourage you to read more in Helium’s <a href="https://docs.helium.com/">documentation</a>.</p><h4>Dataset Curation</h4><p>All the data you will see here was generated by making requests to the publicly-available <a href="https://docs.helium.com/api/blockchain/introduction/">Helium Blockchain API</a>. <a href="https://github.com/helium/blockchain-http/blob/master/LICENSE">Open-source</a> ledgers provide fault-tolerance and auditability, but they are also fantastic datasets for data mining. Here are some example API calls that I implemented with the requests library in Python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4328410e142fec9888549795d8aad21/href">https://medium.com/media/d4328410e142fec9888549795d8aad21/href</a></iframe><h4>What is a Graph?</h4><p>Often, the way we choose <em>represent </em>a dataset is as important as the data itself. Some inputs, like images and financial time series, lend themselves to well-defined representations, like arrays, vectors, and tensors. Since many ML models, like convolutional neural networks, rely heavily on linear algebra, we often prefer matrix-like data structures. However, for many complex applications, such as drug discovery, recommender systems, and of course, <strong><em>wireless networks, </em></strong>we would benefit from a bit less structure.</p><p><strong>Graphs </strong>are a data structure defined by discrete points, called <strong>nodes</strong>, and expressions of adjacency between nodes, called <strong>edges</strong>. For example, you could generate the graph for a molecule, where nodes were individual atoms, and edges are the bonds between them. For our purposes, we can think of the Helium Network as one giant graph, with 200,000+ nodes (Hotspots) and millions of edges (witness paths). Fortunately, there are a number of open-source libraries that help with constructing and analyzing graphs; in this article, I will use the Python modules <a href="https://networkx.org/">NetworkX </a>and <a href="https://pytorch-geometric.readthedocs.io/en/latest/">PyTorch Geometric</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*lpk2mJGfiYaTDPPZQ13CJA.png" /><figcaption>An example of witnesses for a given Helium hotspot (image by author).</figcaption></figure><h4>Generating the Helium Network Graph for a City</h4><p>The following code snippet defines the CityGraph class, which we will use to generate the NetworkX graph for a given city. First, we create a node for each hotspot and include features like their location, elevation, antenna gain, and recent earnings. The index for each node is its unique hotspot address. Next, we loop through all the recent witness receipts for each hotspot and create edges between that node and its unique witnesses. We can even apply weights to the edges, such as metrics about the strength of the signal (e.g. RSSI or SNR) or the reported distance traveled by the packet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/238476c7b92a17b33a2012a09389bcf7/href">https://medium.com/media/238476c7b92a17b33a2012a09389bcf7/href</a></iframe><p>We can then visualize the graphs with the nx.draw() function. Here is an example of the Helium Network’s presence in State College, PA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*AjvAHAdpQFm_XfmoY2cgXg.png" /><figcaption>The graph for the Helium Network’s presence in State College, PA. Nodes represent individual hotspots and edges represent witness paths (i.e. hotspots that can “hear” each other). “Lone wolves” cannot prove their coverage and thus, earn minimal rewards (image by author).</figcaption></figure><h4>Feature Extraction: PageRank &amp; Betweenness Centrality</h4><p>Once we have this representation, we can leverage decades of research in Graph Theory to extract insights about our dataset. <strong>Algorithms that were originally developed for completely different domains may even be applicable to our analysis of wireless networks.</strong> For example, the <a href="http://ilpubs.stanford.edu:8090/422/1/1999-66.pdf"><strong>PageRank </strong></a>metric was designed (in 1999!) as a way for search engines to find the most relevant websites for a given query. In these citation graphs, individual sites are nodes and hyperlinks between sites express adjacency. The most influential websites are those that users end up navigating to most often. Does this have any relevance to an IoT network? Let’s take a look at the PageRank values for the Helium Network in Pittsburgh using plotly .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*khAQuYeDX7xbnAAyTFhxDw.png" /><figcaption>The Helium Network presence in Pittsburgh, colored by PageRank score (image by author).</figcaption></figure><p>The bright yellow nodes are those with the highest PageRank scores, while dark blue points have low scores. Having a lot of witnesses certainly helps your PageRank value, but it is not the only factor. The algorithm also takes into account the relative influence of any connected nodes, as that is an indicator of how well traffic will flow toward that hub (e.g. traffic coming from a high-value site, like CNN.com, is weighted more heavily than traffic coming from my blog). On the other hand, hotspots that are placed in the densest areas, but relatively underperforming their neighbors, are deemed insignificant by the PageRank score.</p><p>Another potentially relevant metric is called <a href="https://en.wikipedia.org/wiki/Betweenness_centrality"><strong>Betweenness Centrality</strong></a><strong> </strong>(or just “betweenness”). In this case, the algorithm uses shortest paths to identify influential nodes. You could apply this to air travel; because of its central location in the continental U.S., Chicago O’Hare is a common layover destination for both east-west and north-south flights. Betweenness has also been used to identify the <a href="https://medium.com/social-media-theories-ethics-and-analytics/network-analysis-from-social-media-data-with-networkx-13605d711590">reddit communities with the highest influence</a> on viral trends, since these are the subs that provide the most direct link between seemingly disparate topics, like politics and pop culture. Again, let’s take a look at this metric as it relates to the Helium Network in Pittsburgh.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*o-DuYFSQWKUjL99zRIvBGw.png" /><figcaption>The Helium Network in Pittsburgh, colored by Betweenness Centrality (image by author).</figcaption></figure><p><strong>The hotspots with the highest betweenness scores are those that uniquely connect geographically sparse regions</strong>, such as those that provide the only witness path between Downtown Pittsburgh and the South Hills. I would contend that these hotspots are lynchpins for the network; although they may not have the highest witness counts, they perform critical proofs of coverage.</p><h4>Outlier Detection: Graph Neural Networks</h4><p>Let’s bring these concepts together with some deep learning. “Graph Neural Networks” (GNNs) encompass a subset of DL models designed to extract insights from — you guessed it — graph-based datasets. Just like with image- and NLP-based AI, researchers are constantly coming up with new variations on GNN algorithms, optimizers, and activation functions to suit various tasks. Rather than dwell on the methods themselves, which are better explained <a href="https://towardsdatascience.com/a-gentle-introduction-to-graph-neural-network-basics-deepwalk-and-graphsage-db5d540d50b3">elsewhere</a>, I want to focus on how we will apply them to our dataset.</p><p>In the Helium Network, one of the premiere challenges for the engineering team is to <strong>identify bad actors</strong> who may be spoofing the system to increase their rewards. This gaming can take many forms, but one of the most popular approaches is to make hotspots appear more spread out then they really are. With sparse placement, miners benefit from optimal rewards scaling, since Proof of Coverage <a href="https://github.com/helium/HIP/blob/master/0017-hex-density-based-transmit-reward-scaling.md">disincentivizes closely-packed hotspots</a>. While the network uses the <a href="http://whitepaper.helium.com/">physical limits of radio propagation</a> to weed out some dishonest activity (i.e. there is an upper limit for the strength of a signal traveling a given distance), it is not incredibly difficult to get around these relatively conservative thresholds in many cases. <strong>The nonlinear nature of deep learning means that the decision boundaries are less predictable and thus, potentially more difficult to circumvent.</strong></p><p>Back to the model itself. Our inputs will be the city graphs we assembled earlier. At the time I generated this dataset, hotspots are placed in over 11,000 unique cities around the world — cities of a wide variety of sizes, geographic features, and regulatory conditions. For each hotspot, we will use the PageRank score and Betweenness Centrality as features, and each witness path will use the RSSI and SNR of the reported beacon as edge weights. Finally, the output of our model will be a regression prediction of each node’s reward scale value. <strong>You can download the full dataset (stored as a pickle binary) </strong><a href="https://drive.google.com/file/d/1fOvY_l8bPuM_uDuxnVSx78Y7HJJUu58H/view?usp=sharing"><strong>here</strong></a><strong>.</strong></p><p>My idea here is that our model should generalize what a “nominal” city looks like, but it will have a hard time classifying outlier cases. In other words, when rewards scales are suspiciously high (or low) given a certain feature set, <strong>our model will show high loss</strong> (measured as mean squared error between predicted and actual). Speaking of the model, here’s the code for our GNN, using PyTorch Geometric’s <a href="https://arxiv.org/abs/1609.02907">GCNConv </a>layers and the Adam optimizer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01dd52fa4b8c29c9dfe8d24ddbcf35ae/href">https://medium.com/media/01dd52fa4b8c29c9dfe8d24ddbcf35ae/href</a></iframe><p>This will print out the cities <em>and </em>individual hotspots from our test set with the highest loss, since we’re making predictions on a node-by-node basis. Let’s use the <a href="https://explorer.helium.com/">Helium Explorer</a> to take a closer look at some of our outliers:</p><p><strong>Outlier City #1: Cardiff, Wales</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ecbL9FjUBPmnjuSqqjEdVg.png" /><figcaption>Impeccably-placed hotspots in Cardiff (image by author).</figcaption></figure><p><strong>Outlier City #2: Cape Coral, FL</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*PzkJnBM4bKolT9lRBO_KKg.png" /><figcaption>Impressive signal propagation in another coastal city, Cape Coral, FL (image by author).</figcaption></figure><p>You can see what the model is getting at. In both of these low-lying coastal cities, most hotspots have <strong>near-optimal rewards scales and impressive signal propagation</strong>. It’s possible there is some spoofing happening here, or maybe this is just an artifact of how well radio waves travel over water. In future models, I would like to account for geographic factors, like local elevation and significant bodies of water.</p><p><strong>Outlier Hotspot #1: Tiny Marmalade Pheasant</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BuXVIgOucap10DAYdcKgXw.png" /><figcaption>Image by author.</figcaption></figure><p><strong>Outlier Hotspot #2: Urban Pine Raven</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*YdlUS05cf4ovTuS62iIkXg.png" /><figcaption>Image by author.</figcaption></figure><p><strong>Outlier Hotspot #3: Boxy Brown Chameleon</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*uCueFcDhJpKnAkM-MNP2Zw.png" /><figcaption>Image by author.</figcaption></figure><p>Now, we’re looking at <em>individual hotspots</em> with the highest loss. In this case, the model is capturing situations where the hotspot is placed in a relatively densely-populated area (i.e. there are lots of other miners nearby), but they still manage a perfect transmit scale. Another phenomena that we see here is some insanely far witness paths, on the order of hundreds of kilometers. Perhaps these hotspots just have extremely powerful antennas and great locations, or maybe this is a sign of suspicious activity.</p><h4>Closing Thoughts</h4><p>In this article, we leveraged Graph Theory to extract insights about the Helium Network. We found that metrics like PageRank and Betweenness, which were originally designed for completely different application domains, have some relevance with respect to finding the most (and least) significant hotspots in a given city. Using these features and state-of-the-art Graph Neural Network-based models, we can start to tackle the formidable task of identifying “suspicious” activity on the Helium blockchain. I am looking forward to further optimizing the model architecture and feature extraction methodologies, as well as extending the classification tasks to other areas, like coverage mapping. In a span of just a couple years, the Helium Network has grown to become the largest public LoRaWAN network on the planet. For folks excited about decentralization and cheap IoT coverage, this is already a massive victory. For data scientists attempting to model this vast (and publicly available) dataset, the work is just beginning.</p><h4>References</h4><p><a href="http://whitepaper.helium.com/">Helium Whitepaper</a></p><p><a href="https://networkx.org/">NetworkX Documentation</a></p><p><a href="https://pytorch-geometric.readthedocs.io/en/latest/index.html">PyTorch Geometric Documentation</a></p><p><a href="https://drive.google.com/file/d/1fOvY_l8bPuM_uDuxnVSx78Y7HJJUu58H/view?usp=sharing">City Graph Dataset (111 MB)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66cbb8bffff9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exploring-the-helium-network-with-graph-theory-66cbb8bffff9">Exploring the Helium Network with Graph Theory</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Privacy Preserving Deep Learning with AWS Nitro Enclaves]]></title>
            <link>https://medium.com/data-science/privacy-preserving-deep-learning-with-aws-nitro-enclaves-74c72a17f857?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74c72a17f857</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 16:19:13 GMT</pubDate>
            <atom:updated>2021-08-13T16:19:13.108Z</atom:updated>
            <content:encoded><![CDATA[<h4>Generate confidential inferences without compromising user data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LS3vCGjaCYU5aYSP" /><figcaption>Photo by <a href="https://unsplash.com/@jdent?utm_source=medium&amp;utm_medium=referral">Jason Dent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The ever-expanding field of confidential computing essentially boils down to two main properties:</p><ol><li><strong>Confidentiality</strong>: How do we perform computational operations on sensitive user data (such as health records and credit histories) without ever “seeing” the data in its unencrypted form?</li><li><strong>Integrity</strong>: If we are able to pull off (1), how do we <em>prove </em>to the user that their privacy was preserved?</li></ol><p>AWS thinks they have the answer in their Nitro Enclave offering, which leverages the <a href="https://en.wikipedia.org/wiki/Trusted_execution_environment">Trusted Execution Environments</a> (TEE’s) on modern processors to create attestable applications that are isolated from tampering by external networks or even the host OS. TEE’s provide confidentiality and integrity, but they are notoriously difficult to use. In this tutorial, we will use the Nitro Enclave platform for a relatively complex task (by confidential computing standards): secure evaluation of a convolutional neural network from a user-supplied image.</p><h4>“Lift and Shift”</h4><p>AWS touts Nitro Enclaves as a “<a href="https://press.aboutamazon.com/news-releases/news-release-details/aws-announces-general-availability-nitro-enclaves">lift and shift</a>” solution, but TEE’s introduce some idiosyncrasies that we will have to address in our application. The good news is that standard docker images can be converted into the “Enclave Image File” (.EIF) format that the enclave expects. We can build relatively rich programs without being constrained to a certain language or OS, and we can allocate almost all of our host’s memory and CPU resources to the TEE. Using the <a href="https://github.com/aws/aws-nitro-enclaves-cli">Nitro CLI</a>, many of the low-level operations are abstracted into a handful of simple commands.</p><p>While these features drastically lower the learning curve for developing confidential applications (especially compared to legacy platforms), it does not mean that you can drop an unmodified docker image into an enclave and expect it to work. The most significant difference is the networking interface — a Nitro Enclave is completely isolated from all external connections, except for a local socket that allows it to communicate with the host instance. While this results in a tamperproof computing environment, it also means that we will have to resort to low-level protocols (e.g. Python’s <a href="https://docs.python.org/3/library/socket.html">socket</a> library) in order to pipe data to and from the enclave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*yheN-gKzPUDVQVhmBys17A.png" /><figcaption>Nitro Enclaves can only communicate with the parent instance through a secure virtual socket (image by author)</figcaption></figure><p>Another problematic byproduct of enclaves’ isolation is that they have difficulty generating entropy. Normal personal computers capture a buffer of random bytes from physical phenomena like spinning disk drives, keyboard strokes, or mouse clicks. This entropy is then spent on operations that rely on true randomness, like encryption and key generation. By contrast, enclaves are designed to boot safely and predictably in order to create reliable attestation documents, which makes entropy a precious commodity. For our application to run smoothly, we will have to figure out a way to “top off” our random buffer.</p><h4>Confidential Classification Scenario</h4><p>The medical field presents an excellent use case for confidential computing, as multiple stakeholders wish to their data private. In this example, we consider an application where patients can query a trained <a href="https://github.com/aryanmisra/Skin-Lesion-Classifier">convolutional neural network</a> to see if they have skin cancer. Users want to ensure that their input and diagnosis are never revealed to the developers, and the developers want to avoid sharing their proprietary model with the users. Our confidential inferencing workflow is shown in the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*XgYjhZGOxehUVjk0zRcprw.png" /><figcaption>Our confidential inferencing workflow, which will allow users to get a skin cancer diagnosis without revealing the input (an image of the skin lesion) to the application (image by author).</figcaption></figure><h4>Setting up the Parent Application</h4><p>For clarity, we will separate the parent application into its two main processes: sending and receiving data. Let’s start with the VsockListener class, which is the server process that accepts messages from the enclave through the virtual socket:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00893d276d4edb75f82e154eb549e801/href">https://medium.com/media/00893d276d4edb75f82e154eb549e801/href</a></iframe><p>In the recv_data_parent function, we define a simple protocol for handling incoming content. Typically, you would add some header bytes or other pre-defined encoding to tell the server what type of information is contained in the transmission, but we will just use the size of the message to determine what data it could contain. The encrypted inference (a number that can be mapped to a diagnosis label) will be about 100 bytes, and the enclave’s public keys are about 400 bytes. The encrypted symmetric key is somewhere in between, about 256 bytes. Check out <a href="https://security.stackexchange.com/questions/10949/encryption-should-i-be-using-rsa-or-aes/10953#10953">this explanation</a> of the hybrid encryption protocol we’re implementing <a href="https://github.com/evandiewald/nitro-enclave-tensorflow/blob/main/crypto_utils.py">here</a>.</p><p>Now, let’s take a look at how the parent will <em>transmit </em>information to the enclave.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0bf01d548694f9bf7e3d2bb618c5656/href">https://medium.com/media/c0bf01d548694f9bf7e3d2bb618c5656/href</a></iframe><p>We will wait to call this class until after the enclave’s public key has been received, since we will need it to asymmetrically encrypt our image. Note that before we send the image or key, we send the length of the subsequent message so that the enclave knows how many bytes to expect (after working with sockets for a few days, you will never take HTTP for granted again!).</p><p>We’ll use an argument parser to run these handlers from the command line, e.g. python3 vsock-parent.py server &lt;port-in&gt; (for the listener) and python3 vsock-parent.py client &lt;enclave-cid&gt; &lt;port-out&gt; (for the client).</p><p>Now let’s take a look at the enclave application code.</p><h4>Setting up the Enclave</h4><p>The enclave application is very similar to the parent application, except that we are going to use a single program to handle both sending and receiving data. <a href="https://github.com/evandiewald/nitro-enclave-tensorflow/blob/main/vsock-enclave-bidirectional.py">Check out the script in the Github repository</a>. I do want to highlight a couple of key differences. First, before we try any encryption or decryption, it’s critical that we generate some entropy using the rng-tools package, for reasons discussed in the introduction. We can start the daemon from within the python script with subprocess.run(‘rngd -r /dev/urandom -o /dev/random’, shell=True) . Without this line, the application <a href="https://github.com/aws/aws-nitro-enclaves-sdk-c/issues/41">just hangs indefinitely</a> at steps that require randomness.</p><p>To save precious memory in our enclave image, I opted for the <a href="https://www.tensorflow.org/lite/guide/python">Tensorflow Lite runtime</a>, rather than the full-fledged Tensorflow installation (which can exceed 2–3GB alone). Wherever possible, try to limit your enclave’s computational overhead, as if you were developing an application for a microcontroller or Raspberry Pi. The code for the invoking the Tensorflow Lite interpreter and generating an inference can be found <a href="https://github.com/evandiewald/nitro-enclave-tensorflow/blob/main/predict_tflite.py">here</a>.</p><p>Finally, let’s take a look at the Dockerfile, which contains the instructions to build our image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baa018bd77a29b7c7c752e3c697d8b50/href">https://medium.com/media/baa018bd77a29b7c7c752e3c697d8b50/href</a></iframe><p>Installing dependencies, copying files, and generating our RSA keypair with ssh-keygen should be relatively straightforward. In the last line, we launch our python application using command line arguments; the CID of the parent instance is <strong>always </strong>3, and we will use ports 5005 and 5006 to send and receive data.</p><p>With our setup complete, let’s talk about implementation.</p><h4>Step-by-Step Demo</h4><p>Launch an EC2 instance that is <a href="https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html#nitro-enclave-reqs">compatible with Nitro Enclaves</a>, such as an m5.4xlarge, and make sure to enable the Enclave option during setup. Remember that we will need enough memory and CPU cores to run both the parent and enclave. While you can use most Linux-based platforms, I recommend Amazon Linux 2 — otherwise, you will have to build the Nitro CLI yourself. Login to your instance via SSH and update with</p><p>sudo yum update</p><p>We will also need to install docker and the Nitro CLI.</p><p>sudo amazon-linux-extras install docker aws-nitro-enclaves-cli aws-nitro-enclaves-cli-devel -y</p><p>Start the docker service.</p><p>sudo service docker start</p><p>Elevate user privileges for docker and nice editor.</p><p>sudo usermod -aG ne ec2-user &amp;&amp; sudo usermod -aG docker ec2-user</p><p>Next, we need to configure the resources (CPU cores and memory) that our enclave will be able to access. Edit the /etc/nitro_enclaves/allocator.yaml file and increase the default values to 8192 MB RAM and 4 cores (though I’m sure you can get away with less). To submit these changes, run</p><p>sudo systemctl start nitro-enclaves-allocator.service &amp;&amp; sudo systemctl enable nitro-enclaves-allocator.service</p><p>At this point, <strong>reboot </strong>your instance to allow the various updates to take effect.</p><p>After the reboot, clone the public repository</p><p>git clone <a href="https://github.com/evandiewald/nitro-enclave-tensorflow.git">https://github.com/evandiewald/nitro-enclave-tensorflow.git</a></p><p>And cd into the repo directory. Build the docker image with</p><p>docker build -t enclave-tensorflow .</p><p>Once the image is created successfully, we use the Nitro CLI to convert it into an EIF file:</p><p>nitro-cli build-enclave --docker-uri enclave-tensorflow:latest --output-file enclave-tensorflow.eif</p><p>If all goes well, you’ll see an attestation document with 3 SHA hashes, which correspond to the enclave image, kernel, and application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Ntmx2nisKjxQkLg73gWP5w.png" /><figcaption>The output from the build-enclave command, showing the hashes of the enclave image, linux kernel, and your application (image by author).</figcaption></figure><p>Before we run the enclave, we need to make sure our parent instance is listening for a connection. Open up a new terminal and run</p><p>python3 vsock-parent.py server 5006 The console should print Server ready!</p><p>Back in the first terminal, let’s finally execute our enclave application. Again, we’ll use the Nitro CLI</p><p>nitro-cli run-enclave --eif-path enclave-tensorflow.eif --memory 8192 --cpu-count 4 --enclave-cid 16 --debug-mode</p><p>A successful output will show some basic metadata about the enclave and its resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*6pvNrKMRWLp5EPEL87TO3A.png" /><figcaption>Output of the run-enclave command, showing which CPU cores and how much memory have been allocated to our secure enclave (image by author).</figcaption></figure><p>Take note of the EnclaveID, which you will need in the next step. As soon as the enclave boots, the server in the other terminal should print out Enclave&#39;s public key received. But it would be nice to know what was going on in our enclave for debugging purposes. Since we included the --debug-mode flag, the Nitro CLI exposes a console that will allow us to view the output from our application and make sure it’s running properly.</p><p>nitro-cli console --enclave-id $ENCLAVE_ID</p><p>You’ll be greeted with a long list of printouts describing the boot operations, but at the bottom you should see some messages from our python application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*YM0EozxisfhX8bve1eBUyQ.png" /><figcaption>The console output from the enclave, which is only available in debug mode. After sending its public key to the parent instance, our application listens for incoming messages (image by author).</figcaption></figure><p>At this point, open up a third terminal and send the user’s data from parent to enclave with</p><p>python3 vsock-parent.py client 16 5005 (16 is the Enclave CID)</p><p>This terminal should indicate that it is sending the parent’s public key, encrypted image, and symmetric key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*O71gocjAwgAmIE-jNHkCQQ.png" /><figcaption>Output of vsock-parent.py after sending messages from the parent instance to the enclave over the virtual socket (image by author).</figcaption></figure><p>Back in the enclave console, the application will acknowledge that it received and decrypted the messages before classifying the image, encrypting the inference, and sending it back to the parent server. At this point the enclave will shut down, giving a connection error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*UvR9UUdIcmGhlgGgmrpmLQ.png" /><figcaption>Back in the enclave console, our isolated application has now received the encrypted image, classified it using the trained model, and sent the user an encrypted inference. All sensitive data is secured when not in the TEE (image by author).</figcaption></figure><p>Finally, the server will receive the inference, decrypt it, and print out the results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*8iYsqTCzbeU3FcyO6kJDBw.png" /><figcaption>The input image of a skin lesion was correctly classified as an example of Basal Cell Carcinoma. This diagnosis is not visible to the application developers, only the patient (image by author).</figcaption></figure><p>Don’t forget to terminate your EC2 instance to prevent further charges.</p><h4>Final Thoughts</h4><p>In this tutorial, we saw how <strong>TEE’s enable two distributed stakeholders to share data without an assumption of explicit trust.</strong> Nitro Enclaves are a triumph of hardware, software, and advanced cryptography, but as soon as you incorporate a bit of complexity, they can cause some unique headaches. I have never had to worry about sockets or entropy before, and debugging enclave images is a painful process compared to standard docker containers. After completing this project, I am not surprised that the only other tutorials I can find are for “hello world” applications. While this demo is far from optimal, I hope it serves as a useful starting point for your own, robust <em>Secure Multi-Party Computation</em> platforms.</p><p>Check out the full project code on my <a href="https://github.com/evandiewald/nitro-enclave-tensorflow">Github page</a>.</p><h4>References</h4><p>Nitro Enclaves User Guide: <a href="https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html">https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html</a></p><p>AWS VSock Sample on Github: <a href="https://github.com/aws/aws-nitro-enclaves-samples/tree/main/vsock_sample/py">https://github.com/aws/aws-nitro-enclaves-samples/tree/main/vsock_sample/py</a></p><p>Trained Skin Lesion Classifier Model (I converted the h5 model weights to a TFLITE model): <a href="https://github.com/aryanmisra/Skin-Lesion-Classifier">https://github.com/aryanmisra/Skin-Lesion-Classifier</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74c72a17f857" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/privacy-preserving-deep-learning-with-aws-nitro-enclaves-74c72a17f857">Privacy Preserving Deep Learning with AWS Nitro Enclaves</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Decentralized Ticket Exchange Using the Flow Blockchain]]></title>
            <link>https://medium.com/better-programming/build-a-decentralized-ticket-exchange-using-the-flow-blockchain-ed0eaf7745d0?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed0eaf7745d0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Thu, 29 Jul 2021 16:01:56 GMT</pubDate>
            <atom:updated>2021-07-29T16:05:12.339Z</atom:updated>
            <content:encoded><![CDATA[<h4>Adding utility to NFTs using Dapper Labs’ promising new platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuAw75ZRPaofAaasZI6YHg.png" /><figcaption><em>The Cube</em>, by artist Pak (<a href="https://niftygateway.com/itemdetail/primary/0xc7cc3e8c6b69dc272ccf64cbff4b7503cbf7c1c5/4">Source</a>)</figcaption></figure><p>Since the advent of the ERC-721 standard in 2017, Non-Fungible Tokens (NFTs) have matured from an experimental platform for trading virtual cats to a massive industry with mainstream adoption.</p><p><a href="https://www.nba.com/news/dapper-labs-creators-of-nba-top-shot-get-305m-in-funding">NBA Top Shot has raised $305 million</a> to sell NFTs representing basketball highlights for their 800,000+ users, and <a href="https://www.sothebys.com/en/articles/17-million-realized-in-sothebys-first-nft-sale-with-digital-creator-pak">Sotheby’s just auctioned a piece of digital art for $17 million</a>.</p><p>It’s clear that NFTs are here to stay, but even as a crypto fan, I still struggle with the value proposition of the digital art model.</p><p>When you buy an NBA Top Shot collectible, you don’t own the commercial rights to the highlight. You don’t even get exclusive rights to share it. In fact, here’s that $17M piece of art, free of charge.</p><p>But let’s talk about what you <em>do </em>get with an NFT: cryptographically-verifiable ownership of a unique asset and smart contract-defined capabilities for selling or transferring said asset.</p><p>Lots of asset types would benefit from cryptographically-verifiable ownership: transcripts, certifications, and intellectual property come to mind (imagine replacing the USPTO with a blockchain…skip the lawyers and submit your application as a first-come, first-served transaction).</p><p>It was at a friend’s suggestion that I started thinking about event tickets as a candidate for an NFT asset class, which makes a lot of sense. What are the biggest problems in the ticket marketplace? To name a few:</p><ul><li>Counterfeits</li><li>Massive transaction fees (we all know the feeling of seeing tickets listed for $50, but somehow spending $72.50 by the time Ticketmaster takes their cut)</li><li>Unregulated secondary markets</li></ul><p>These problems disappear if we use smart contracts to govern our assets. Establishing authenticity of an NFT is trivial. Transaction fees can be radically reduced if we use the right blockchain.</p><p>To me, the most exciting benefit is the ability for the ticket issuer to set the terms of secondary markets. You can make your assets non-transferrable, make sure they can only be sold for less than the list price, or even give the performers a cut on any secondary sales.</p><p>In this decentralized system, everyone has a fairer and more transparent experience. So let’s get building.</p><h3>Overview</h3><p>The first decision we have to make is about which blockchain platform to use. We could use Ethereum, but transaction fees can be a bit high (though this will change significantly with the coming launch of ETH 2.0).</p><p><a href="http://onflow.org/">Flow</a> is a new blockchain with a developer-friendly ecosystem and negligible transaction fees, which sounds like a great place to start.</p><p>In fact, Dapper Labs’ NBA Top Shot uses <a href="https://github.com/dapperlabs/nba-smart-contracts/tree/master/contracts">Flow smart contracts</a> not unlike what we will deploy here.</p><p>On a high level, here’s what we have to do to create a basic, but functional ticket “marketplace” (we’ll stop short of implementing full buy/sell functionality, but this will hopefully be the subject of a future demo).</p><ol><li>Define the terms of our non-transferrable “Non Fungible Ticket” in a Flow smart contract</li><li>Create dummy accounts to allow an issuer and attendee to interact with our NFTs</li><li>Use transactions to securely demonstrate common functions, like minting and transferring tickets</li><li>Build a barebones frontend with React.js for a simple web interface</li></ol><h3>Setup</h3><p>I used tutorials from the <a href="https://docs.onflow.org/cadence/tutorial/01-first-steps/">Flow documentation</a> as a great starting point for getting familiar with their smart contract programming language, Cadence, and their standard NFT template. If you’re following along, you’ll need to <a href="https://docs.onflow.org/flow-cli/install/">install the Flow CLI</a> for your OS.</p><p>Of course, we could deploy our contract to the Flow mainnet or testnet, but we’re going to take advantage of the <a href="https://docs.onflow.org/emulator#gatsby-focus-wrapper">Flow emulator</a> for rapid local development. Launch the emulator with:</p><pre>flow emulator start</pre><h3>Non-Fungible Ticket Smart Contract</h3><p>Our Non Fungible Ticket smart contract needs to define the characteristics of our NFT as well as functions for minting, storing, transferring, and inspecting them.</p><p>Some capabilities will be made public, like depositing (i.e. I won’t need explicit permission from you to send you a ticket) or getting metadata, while others, like withdrawing and minting, will be privileged (for obvious reasons).</p><p>I also want to make sure that our ticket is non-transferrable, so we will apply a condition that will not allow it to be deposited more than once. Let’s take a look at our Cadence smart contract.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6147aeb75751fa5ee10880c95bf7ab56/href">https://medium.com/media/6147aeb75751fa5ee10880c95bf7ab56/href</a></iframe><p>The Flow docs will provide a clearer explanation than I can, but on a high level, Cadence uses concepts called Resources and Capabilities to define who can access what.</p><p>For instance, we save the NFTCollection and NFTMinter resources to the deploying account’s /storage/ path, which means they are private, but we publish a link to the NFTReceiver capability in the /public/ path. Also note that our NFTs are simply defined by their integer ID and a numTransfers counter that will iterate each time the NFT is deposited.</p><p>In this case, if someone tries to transfer our tickets a second time, the transaction will fail. Save the contract to a directory called cadence/contracts/ .</p><p>Before we deploy our contract, we need to create our flow.json document to specify what is being deployed, by whom, and where it will end up (e.g. in the emulator). To initialize this file in your project directory, run the following command:</p><pre>flow init</pre><p>This also gives us a starter account and a private key. We’ll take a look at the flow.json file in a moment, but first, we will need to create a second account for our attendee. Run the following code to get a public/private key pair:</p><pre>flow keys generate</pre><p>Save both the keys and then run:</p><pre>flow accounts create ATTENDEE_PUB_KEY</pre><p>Replace ATTENDEE_PUB_KEY with the public key you’d just generated.</p><p>Take note of the address, which starts with 0x. Now we have everything we need to complete our flow.json file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/453b4d93112fc318e00fbdc1dd6242ae/href">https://medium.com/media/453b4d93112fc318e00fbdc1dd6242ae/href</a></iframe><p>Note: As general practice, you should never share your private keys. In this case, any keys you see were only valid on the specific instance of my emulator session.</p><p>You’ll see we added a pointer to our NonFungibleTicket contract, our new attendee account, and a deployment of our contract by the emulator-account (representing our ticket issuer) to the emulator. At this point, we can deploy our contract with:</p><pre>flow project deploy</pre><p>If all goes well, you should see an output like this:</p><pre>Deploying 1 contracts for accounts: emulator-account</pre><pre>NonFungibleTicket -&gt; 0xf8d6e0586b0a20c7</pre><pre>✨  All contracts deployed successfully</pre><h3>Minting our NFT</h3><p>Now it’s time to actually create our first NFT. Again, we are going to use Cadence, but instead of defining a contract, we will use a transaction. Transactions are how we use the functions defined in the smart contract to make changes to the blockchain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dccea6d722c93fb00b1f7ef918e5e161/href">https://medium.com/media/dccea6d722c93fb00b1f7ef918e5e161/href</a></iframe><p>To me, the interesting part of this is the NFT metadata. I created a demo ticket with some attributes like the section and row, and a URI linking to an image of the ticket.</p><p>This brings up a point that I don’t know if a lot of casual NFT users understand about how they work.</p><p>The blockchain is going to do an excellent job of keeping track of who owns this NFT and its associated metadata. However, the common practice with digital assets is to use external storage to store the actual content they represent.</p><p>As an owner of the S3 bucket where the image is stored, nothing is stopping me from deleting or updating the file!</p><p>Imagine if you spent $30,000 on a Steph Curry game-winning 3-pointer and Dapper Labs decided to swap it out for an Alex Caruso free throw. Hopefully, decentralized storage options like IPFS solve this sort of problem.</p><p>Our ticket issuing account deployed the contract, and as such, they have the NFTMinter resource in their private storage. So this account must be the one to sign this transaction:</p><pre>flow transactions ./cadence/transactions/MintTicket.cdc send --signer emulator-account</pre><p>If we tried to sign with attendee-account , the transaction would fail. Next, let’s use a Cadence script (a read-only transaction) to check the balance of our issuer account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3013585ce69ecd80ba652a50328ac440/href">https://medium.com/media/3013585ce69ecd80ba652a50328ac440/href</a></iframe><p>Run the script with the following command:</p><pre>flow scripts execute ./cadence/scripts/CheckTicketBalance.cdc</pre><p>And you should see an array with the ID’s of any owned NFTs:</p><pre>Result: [1]</pre><p>This means that the issuer now owns our newly-minted NFT!</p><h3>Transferring our NFT</h3><p>Now we’ve just got to get our ticket into the hands of an eager concertgoer. First, we’re going to create an NFTCollection resource in the attendee’s storage.</p><p>This brings up a useful aspect of Flow’s infrastructure.</p><p>In Ethereum, if you send ETH to an invalid wallet address, it simply disappears. With Flow, resources cannot be left hanging without having an explicit destination, or else the entire transaction reverts. We won’t lose this ticket if we accidentally send it to an invalid address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b73f412b92ef36b2e4cc1164e6d1072c/href">https://medium.com/media/b73f412b92ef36b2e4cc1164e6d1072c/href</a></iframe><p>Run the above transaction with the following command:</p><pre>flow transactions send .\cadence\transactions\SetupEmptyCollection.cdc --signer attendee-account</pre><p>Now our attendee is ready to receive their ticket. We’ll do this with a Cadence transaction where the issuer account withdraws the NFT from their storage and deposits it in the attendee’s collection.</p><p>Remember that each time a deposit is made, it iterates the numTransfers parameter stored in the NFT. After this transaction, numTransfers = 1 . Here’s how that contract looks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab0175a7dee582346218aadbdbd85b54/href">https://medium.com/media/ab0175a7dee582346218aadbdbd85b54/href</a></iframe><p>Transfer the ticket with the command given below:</p><pre>flow transactions send ./cadence/transactions/TransferTicket.cdc --signer emulator-account</pre><p>You can run the CheckTicketBalance script again for both accounts and verify that getIDs() returns an empty array for the issuer account, and [1] for our attendee! Let’s see what happens if I try to transfer the ticket <em>back </em>to the issuer (or anyone else):</p><pre>❌ Transaction Error<br>execution error code 100: Execution failed:<br>error: panic: Ticket is non-transferrable!<br>  --&gt; f8d6e0586b0a20c7.NonFungibleTicket:59:16<br>   |<br>59 |                 panic(&quot;Ticket is non-transferrable!&quot;)<br>   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre><p>Our smart contract is being properly enforced. Our tickets cannot be transferred on the secondary market.</p><h3>React App</h3><p>I’m not going to get too deep into the details of the frontend application (I’m new to JS, so the code is largely adapted from <a href="https://medium.com/pinata/how-to-display-your-nft-collection-like-nba-top-shot-with-flow-and-ipfs-6ba75048bf8a">this excellent blog</a>), which utilizes the Flow Javascript library to interact with our contract.</p><p>We essentially run Cadence transactions within the application. In this basic example, we’ll just retrieve the metadata, but any Cadence code could be executed in this way.</p><p>Here’s how that looks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be2e9f656adb492b2c7af2c2ab80e0c8/href">https://medium.com/media/be2e9f656adb492b2c7af2c2ab80e0c8/href</a></iframe><p>Run our app locally with:</p><pre>npm run start</pre><p>And we’ll be directed to our simple, but powerful decentralized ticket-viewing webpage.</p><figure><img alt="A decentralized ticket-view output image" src="https://cdn-images-1.medium.com/max/833/1*c3ee9RVNUsU87H76_YXDmA.png" /><figcaption>Image by author</figcaption></figure><p>The full project code is available <a href="https://github.com/evandiewald/flow-ticket-transfer">here</a>. I hope you enjoyed it.</p><h3>References</h3><p><a href="https://docs.onflow.org/cadence/tutorial/04-non-fungible-tokens/">Flow Docs</a></p><p><a href="https://medium.com/pinata/how-to-display-your-nft-collection-like-nba-top-shot-with-flow-and-ipfs-6ba75048bf8a">How to Display Your NFT Collectibles Like NBA Top Shot With Flow and IPFS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed0eaf7745d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-a-decentralized-ticket-exchange-using-the-flow-blockchain-ed0eaf7745d0">Build a Decentralized Ticket Exchange Using the Flow Blockchain</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[Tutorial: MongoDB User Authentication with Google Sign-In]]></title>
            <link>https://medium.com/data-science/tutorial-mongodb-user-authentication-with-google-sign-in-fcc13076799f?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc13076799f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Thu, 29 Jul 2021 14:25:06 GMT</pubDate>
            <atom:updated>2021-07-29T14:25:06.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to simplify your application’s access control and personalize user experience.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7g6jTmutarQ5foCs" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>MongoDB has quickly become my nonrelational database platform of choice for its high performance, broad developer support, and generous free tier. As is the case with many database engines, user management and access control can get quite complex, especially when the software stack draws on other resources, like microservices or cloud storage. Fortunately, we can leverage so-called “federated identity providers” like Google, Facebook, and Amazon to decouple user authentication from the rest of the application.</p><p>In this tutorial, we’ll walk through all the steps necessary to build a secure MongoDB-powered application from scratch. Users will need to sign in with their Google account to read from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CuW2GvwcLnxA7eWiiGxUQ.gif" /><figcaption>By the end of this tutorial, we will have a simple web app that allows users to view a Fruit Marketplace by logging in with their Google account (image by author).</figcaption></figure><p>Before we can write a line of code, we have to setup our cloud-based authentication flow, which involves coordination between Google Identity, AWS IAM, and of course, our MongoDB cluster.</p><h4>Registering a Google Application</h4><p>The first thing we need to do is register our application with Google. In addition to piggybacking off existing security infrastructure (and legitimizing the login page with a familiar interface), this will enable us to personalize the user experience by viewing customers’ profile information.</p><p>First, login to the <a href="https://console.cloud.google.com/getting-started">Google Cloud Console</a>, create a new project, and give it a descriptive name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*POvQmjhlYCsymBEAVihJMw.png" /><figcaption>Creating a new project in the Google Cloud Console (image by author).</figcaption></figure><p>Once your new project is initialized, search for “APIs &amp; Services”, navigate to the “OAuth consent screen” tab in the sidebar, and click “Create an External User”. On the first page of the setup wizard, you’ll need to provide an application name and an email address for user support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*mMsyctNuBBiQpGzqmKZ_mQ.png" /><figcaption>Configuring the OAuth consent screen, which will notify users what permissions our application is requesting (image by author).</figcaption></figure><p>The next page is where we will define our application scope, which dictates exactly what aspects of a user’s Google account we will have permission to read or modify. This is one of the most consequential steps of the entire process, as we could request users’ contact information, calendars, location, or other personal content. In this demo, our app will be able to read a user’s email address and profile, which includes their name and avatar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*CPLM0Zh153JMGagJAEzwZw.png" /><figcaption>Enabled scopes for the application — in this case, read access to users’ email and profile (image by author).</figcaption></figure><p><strong>Important note</strong>: In a production environment, you will need to provide a Privacy Policy and other legal documentation to define exactly how this personal information will be used.</p><p>Next, assign at least one test user. Until our app is officially approved for public access by Google, login access will be restricted to these accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EP9m4IsDWfVTzv2PJe9LhQ.png" /><figcaption>Assigning test users is necessary until our app has been officially published by Google (image by author).</figcaption></figure><p>Once we’ve established the OAuth consent screen, we need to generate a Client ID for our Google app. Still within APIs &amp; Services, navigate to the “Credentials” tab in the sidebar. Under “Create Credentials”, select “OAuth client ID”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*KJbTAtkv4AHJDddbZuQkbw.png" /><figcaption>Creating an OAuth client ID on the Credentials tab (image by author).</figcaption></figure><p>Initialize the client as a web application and add <a href="http://localhost:8000/">http://localhost:8000</a> as an authorized JavaScript origin, since the login request will be made from our local development server (more on this later).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ZdN6dVSgwcb3jFIzcyN5zA.png" /><figcaption>Configuring the Client ID credentials (image by author).</figcaption></figure><p>This will generate your app’s client ID (something like 1234567890.apps.googleusercontent.com). We will need this in a couple different places, so paste it somewhere for easy access.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*HbsZR3jKKSzqyfCUBjGXDQ.png" /><figcaption>Copy the Client ID (image by author).</figcaption></figure><p>This completes the Google Console part of the process. Now onto AWS.</p><h4>Create an IAM Role in AWS</h4><p>Once your application has been registered with Google, log into your <a href="https://console.aws.amazon.com/">AWS Console Account</a>. Search for “IAM”, select “Roles” in the sidebar, and click “Create Role”. For the type of trusted entity, select “Web Identity” and choose Google as the identity provider (you’ll notice that we can use a similar flow for Facebook, Amazon, and other federated identity providers). Paste your Google Client ID under Audience. Accept the defaults for the rest of the Role setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*KaEXwbrzMHitAHqs0qJCJQ.png" /><figcaption>In AWS IAM, create a new role with Google as the identity provider (image by author).</figcaption></figure><p>Once your Role has been created, take note of the Role ARN (e.g. arn:aws:iam::AWS_ACCOUNT:role/roleName), which we’ll need in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*AHdJorhl7irNQ8qDp-HdQA.png" /><figcaption>One place to find the Role ARN (image by author).</figcaption></figure><p>This completes the AWS setup required for this demo, but I will make the note that by adjusting the Policy Document attached to this Role, we can connect our application to other AWS resources, like S3 buckets and Lambda functions.</p><h4>Configuring the MongoDB Database</h4><p>Next, we need to launch and configure our cloud-based MongoDB cluster. Log into <a href="https://account.mongodb.com/account/login">MongoDB Atlas</a> and create an organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*-HK0xRRZUgBw8-bxs2tImw.png" /><figcaption>Initializing a new organization in MongoDB Atlas (image by author).</figcaption></figure><p>Within your Atlas organization, create a new project and give it a name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*If222VoC5yMSZOiuRPXHZg.png" /><figcaption>Create a new project (image by author).</figcaption></figure><p>Finally, create a database. For this demo, I’ll be using a free Shared Cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*bqORmC30yCqJ7oAVi5HOdQ.png" /><figcaption>I opted for the (free) Shared Tier (right-most option) (image by author).</figcaption></figure><p>Make sure to select AWS as the cloud provider and the M0 Sandbox Tier (also free) for this cluster. You shouldn’t have to connect a credit card unless you opted for upgraded capacity, which isn’t necessary for our simple demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Pn_BhH2nqvCIRJfybRlH2w.png" /><figcaption>Deploy the cluster to the AWS region of your choice and make sure the use the M0 Sandbox Tier to use the database for free (image by author).</figcaption></figure><p>Grab a cup of coffee while your cluster is deployed. When it’s ready, click the “Collections” tab. If you’re unfamiliar with MongoDB syntax, “Collections” are akin to SQL tables, and “Documents” can be thought of as JSON-based entries or rows within tables. The first time you create a new collection, you’ll have the option to use a sample dataset or add your own. We’ll opt for the latter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*0j0gJ-y2h4uMOhuui4L4Ew.png" /><figcaption>Creating a new database and collection (image by author).</figcaption></figure><p>Let’s say our app is a fruit marketplace that stores the names, prices, and remaining quantities of various items. We’ll insert a few documents into the “marketplace” collection within the “test” database. The quickest way to do this is directly within the web interface, but you can also perform bulk insertions through the <a href="https://docs.mongodb.com/mongodb-shell/">MongoDB shell</a> or <a href="https://docs.mongodb.com/drivers/">one of their many supported drivers</a>. Since this tutorial is more focused on authentication, I won’t dwell on schema or usage within MongoDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*WxYXoZx6ylhlelOXBTbz3Q.png" /><figcaption>Inserting documents into our MongoDB collection within the web interface. You can also test out queries fom this page (image by author).</figcaption></figure><p>Finally, let’s connect our database to our IAM Role. On the side tab go to “Database Access” and add a new database user. For the Authentication Method, select “AWS IAM” and choose “IAM Role” in the “AWS IAM Type” dropdown menu. Paste the Role ARN in the required input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*tKQ31wQ-IfOox0-g6J2nnw.png" /><figcaption>Adding a new database user with AWS IAM credentials (image by author).</figcaption></figure><p>Adjusting user privileges is another complex topic that warrants its own blog entirely. We’ll give this user read-only access to the “marketplace” collection that we just created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*vc6ZS6q6u3LVe_4KtRhaNg.png" /><figcaption>Restricting this user’s privileges to read-only access of the test.marketplace collection (image by author).</figcaption></figure><p>In addition to user-based authentication, MongoDB can also restrict access to specific IP addresses. In a production environment, we would only want to allow requests that come from our application’s servers, to help thwart threats like DDoS attacks. Since we’ll be running the demo application locally, under “Network Access”, <strong>add only your current IP address</strong>, following the <a href="https://en.wikipedia.org/wiki/Principle_of_least_privilege">principle of least privilege</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1lwIwEEd2-kOyVQZx_OMA.png" /><figcaption>Restrict network access to only the IP addresses that absolutely need it (image by author).</figcaption></figure><h4>Putting it all together in a demo application</h4><p>With the setup complete, we are finally ready to write some code. If all goes well, signing in with our Google account will return an ID token that can be used to retrieve credentials for the AWS IAM Role. Our application’s server will then use those credentials to read from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*0wzvp2DdzkmLgasijkV20g.png" /><figcaption>The 30,000-foot view of our application flow (image by author).</figcaption></figure><p>Client-side, we sign in, retrieve the credentials, send them to our backend, and use the response to update the webpage (the following snippet is taken from our <a href="https://github.com/evandiewald/mongodb-google-auth/blob/main/templates/index.html">index.html</a> file).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da99dc065cd7a295a1bf93dcf6234279/href">https://medium.com/media/da99dc065cd7a295a1bf93dcf6234279/href</a></iframe><p>Notice that within the signinCallback function, we’re sending a POST request containing the AWS credentials to the /fruits endpoint (again, we’re simplifying things for this demo by using an HTTP server — in production you would want to encrypt this connection in transit with HTTPS). That request will be processed by our FastAPI-based webserver like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b49e1fe0a718f5c0b63423b16cb3a96/href">https://medium.com/media/6b49e1fe0a718f5c0b63423b16cb3a96/href</a></iframe><p>As mentioned previously, while I opted for a Pythonic implementation, MongoDB supports drivers in dozens of programming languages, so you may prefer to build a scalable server in Go, Node.js, or Rust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CuW2GvwcLnxA7eWiiGxUQ.gif" /><figcaption>The “fruits” of our labor: a simple, but personalized and secure application (image by author).</figcaption></figure><p>And there you have it! While a simple demonstration, this infrastructure can easily be extended to support other identity providers or additional AWS resources.</p><p>Full sample code is available on my <a href="https://github.com/evandiewald/mongodb-google-auth">Github page</a>.</p><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><h4>References</h4><p>[1] “Welcome to the MongoDB Documentation — MongoDB Documentation.” <a href="https://docs.mongodb.com/">https://docs.mongodb.com/</a> (accessed Jul. 28, 2021).</p><p>[2] “Integrating Google Sign-In into your web app.” <a href="https://developers.google.com/identity/sign-in/web/sign-in">https://developers.google.com/identity/sign-in/web/sign-in</a> (accessed Jul. 28, 2021).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc13076799f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/tutorial-mongodb-user-authentication-with-google-sign-in-fcc13076799f">Tutorial: MongoDB User Authentication with Google Sign-In</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Ethereum Token to Enable a Decentralized Rent-to-Own Network]]></title>
            <link>https://medium.com/data-science/creating-an-ethereum-token-to-enable-a-decentralized-rent-to-own-network-cc3786cf1142?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3786cf1142</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[metamask]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[rent-to-own]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 20:35:26 GMT</pubDate>
            <atom:updated>2021-07-24T11:55:49.347Z</atom:updated>
            <content:encoded><![CDATA[<h4>The most sustainable applications of cryptocurrencies involve re-thinking how we establish trust in everyday relationships.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urYhRwQ0nuz_c2qK5UP0fQ.png" /><figcaption>Image by author.</figcaption></figure><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><h3>Introduction</h3><p>With real estate prices soaring to record heights, it has never been more difficult to qualify for a mortgage. Even those with steady, well-paying jobs can struggle to prove their creditworthiness and save up enough cash to start building equity in a home. <a href="https://www.investopedia.com/updates/rent-to-own-homes/">Rent-to-Own</a>, as the name implies, is an alternative route to homeownership in which renters have the option to purchase the property when their lease expires. While the terms of the agreement can vary, what this essentially means is that a certain portion of each rent check goes toward an eventual down payment. Ideally, this arrangement is a win-win: landlords benefit from extra-motivated tenants, and dependable renters are rewarded for their financial responsibility. However, in practice, Rent-to-Own is far from perfect. Renters who decide to move have to forfeit their accrued payments and start over. Predatory landlords change the terms at the last minute, and both parties must rely on each other to keep honest and accurate records.</p><p>Fortunately, innovations in Decentralized Finance (DeFi) offer a potential solution to these problems. Using smart contracts, we can program the business logic of rent-to-own agreements as independently-verifiable transactions in an immutable ledger. We can even create an cryptocurrency-based incentive system that rewards both renters and landlords. These are the principles behind the <strong>RTO </strong>token, the non-transferrable asset class that drives a potential <em>network </em>of Rent-to-Own participants. Let’s start with a conceptual overview of the (preliminary) economics before diving into technical details.</p><h4>Motivation</h4><p>For the RTO system to work, it must benefit all stakeholders. First, landlords who list a home through any rent-to-own scheme expect to make a certain amount of cash during the rental period before the sale. Typically, this represents some portion of the property’s appraisal value. Once this threshold is met, they want to sell to a motivated, creditworthy buyer. But how do you go about finding such a buyer? Credit scores do not tell the whole story, and references can be easily forged. Because of the difficulty in establishing trust through these imperfect metrics, landlords often have no choice but to allow each tenant to prove themselves through firsthand experience (i.e. years of on-time payments). For this reason, most rent-to-own agreements are non-transferrable, meaning that tenants have to return to square one if they decide to move.</p><p>Thus, a ubiquitous <em>network </em>of rent-to-own homes and participants would be advantageous. Property management companies would be one way to achieve this, but such centralized options remove individuals’ autonomy in exchange for standardization and shared infrastructure, like secure payment platforms and databases. RTO offers a decentralized alternative. We start by leveraging the secure, stable, and immutable financial transactions that are already baked into the Ethereum ecosystem, wrapping our business logic in a smart contract to establish trust among distributed network participants.</p><h4>The RTO Smart Contract</h4><p>Our smart contract is simple, but powerful. To list a rent-to-own home on the RTO network, landlords must first be verified by the contract administrator. Once approved, they can add their rental property, which is defined by the renter’s ETH address, an earnings threshold (representing a USD amount that they would like to recover before selling the home), and an earnings percentage (the fraction of each rental payment that will contribute toward the earnings threshold). New homes and renters are initialized with an empty RTO balance, and <strong>homes will not be sold until both buyer <em>and </em>seller have an RTO balance that exceeds the earnings threshold</strong>. This condition ensures that landlords are guaranteed a certain amount of profits and renters have proven themselves creditworthy.</p><p>Each time rent is paid (in ETH) through this smart contract, both the renter <em>and </em>home acquire non-transferrable, dollar-normalized RTO. The exact amount of RTO earned is determined by the following equation:</p><pre>amountToMint = rentAmountEth * earningsPercent * usdPriceEth</pre><p>So let’s say a home has a monthly rent of $2000 (market value of about 1 ETH at the time of writing), an earnings percentage of 20%, and an earnings threshold of $20,000. With each payment, 1 ETH * 20% * ($2000/ETH) = 400 RTO are added to the balances of both renter and home. At this rate, the renter will have the opportunity to purchase the house after about 4 years of steady payments. If they decide to move, both tenant and home retain their RTO balance. It’s important to note that <strong>valid rent payments are the only way to acquire RTO — </strong>tokens are non-transferrable, non-burnable, and cannot be swapped on secondary markets, as opposed to standard ERC20 coins. Like a credit score, there are no shortcuts to establishing good financial standing.</p><p>By making the critical information publicly available, the RTO network creates a competitive marketplace where, in addition to amenities and square footage, participants can compare and negotiate the terms of the earnings agreement. Even within the contract’s relatively simple boundaries, dozens of unique, mutually-beneficial scenarios can occur naturally, such as:</p><ul><li><em>Renter and home both start with 0 RTO and renter does not move</em>: This represents the traditional rent-to-own structure. Both entities reach the earnings threshold at the same time, at which point the renter can buy the house.</li><li><em>Renter RTO &gt; Earnings Threshold &amp; Home RTO &lt; Earnings Threshold</em>: Renter is ready but landlord is not. By the time both conditions are met, the renter may have enough leverage to negotiate for more a more favorable mortgage (e.g. 20 instead of 30-year term).</li><li><em>Home RTO &gt; Earnings &amp; Renter RTO &lt; Earnings Threshold</em>: The opposite of the last scenario. Here, the renter still has to prove themselves, but they may wish to accelerate their earnings by negotiating for a higher earnings percentage.</li></ul><h3>Code and Tutorial</h3><p><a href="#aaca">Skip this section</a> if you’d like to get right to the demo of the decentralized application.</p><h4>Deploying the Smart Contract</h4><p>The business logic discussed above is codified in the following smart contract, written in Solidity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b939478a203527ff47d5747f4521bf0/href">https://medium.com/media/0b939478a203527ff47d5747f4521bf0/href</a></iframe><p>If you’re familiar with object-oriented programming languages, most of the code should be pretty straightforward. I would like to highlight a couple of key functions:</p><ul><li><strong>getThePrice()</strong>: RTO should be pegged to the dollar to account for the volatility in the price of ETH. To normalize ETH payments, we need a way to access the current USD/ETH market price. Unfortunately, we can’t just call the CoinGecko API within Solidity, but we can access a “Price Feed”, which cleverly stores the price on-chain via a Chainlink aggregator interface. <a href="https://docs.chain.link/docs/get-the-latest-price/">More on that here.</a></li><li><strong>payRent(address _to)</strong>: This is the heart of the smart contract, so it deserves special consideration. First of all, we make sure that the payment is made from the home’s renter to its verified landlord. Next, as a payable function, we also facilitate the transfer of ETH (L119), the amount of which is stored in the transaction data. Finally, we calculate amountToMint (see the equation above) and update the balances of home and renter accordingly.</li></ul><p>I deployed the smart contract to the Ropsten Testnet using the Remix IDE and my Metamask wallet. <a href="https://remix-ide.readthedocs.io/en/latest/run.html#run-setup">Here</a> are more detailed instructions if you’re interested. Before we move on to the application, we (as the contract deployer) need to add a verified landlord and sign the transaction using the same account that deployed the contract (representing a trusted administrator). We can do that right in Remix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*gh2J4bcfSq1_WFnaBTUuMA.png" /><figcaption>Image by author.</figcaption></figure><p>We can also view our contract and all associated transactions <a href="https://ropsten.etherscan.io/address/0xf2433ed43d36b5b8f54db39ab2aafc397f13c695">on Etherscan</a>.</p><h4>Application Infrastructure and Metamask Integration</h4><p>The application provides methods for us to use the smart contract functions through a payment portal-esque interface. I’m using Python’s FastAPI to create the API endpoints, the Web3.py library to <em>prepare </em>(but not sign, more on that in a second) the Ethereum transactions, and a basic PostgreSQL database to store some off-chain data, like URL’s to images of the homes. Rather than asking the user to hard-code their private keys into the application itself (a SERIOUS security risk), we sign transactions using the popular <a href="https://metamask.io/">Metamask </a>browser extension. For example, we generate the transaction data for the payRent function like this:</p><pre># from transactions.py</pre><pre>def payRent(landlord, amount_eth):<br>    txn_dict = to_contract.functions.payRent(w3.toChecksumAddress(landlord)).buildTransaction({<br>                &#39;chainId&#39;: 3,<br>                &#39;value&#39;: w3.toWei(float(amount_eth), &#39;ether&#39;),<br>                &#39;gas&#39;: 2000000,<br>                &#39;gasPrice&#39;: w3.toWei(&#39;2&#39;, &#39;gwei&#39;)<br>    })<br>    return txn_dict</pre><p>We can then send this data to Metamask with a few lines of JavaScript:</p><pre># from confirm_transaction.html</pre><pre><strong><em>sendTxnButton</em></strong>.addEventListener(&#39;click&#39;, () =&gt; {<br>  <strong><em>sendTxnButton</em></strong>.disabled = true;<br>  <strong><em>sendTxnButton</em></strong>.innerHTML = &quot;Connecting to Metamask...&quot;;<br>  ethereum<br>    .request({<br>      method: &#39;eth_sendTransaction&#39;,<br>      params: [<br>        {<br>          from: ethereum.selectedAddress,<br>          to: &quot;{{contract_address}}&quot;,<br>          value: &quot;{{value}}&quot;,<br>          gasPrice: &#39;0x4A817C800&#39;,<br>          gas: &#39;0x1E8480&#39;,<br>          data: &quot;{{txn_data}}&quot;,<br>          chainId: &#39;0x3&#39;<br>        },<br>      ],<br>    })<br>    .then((txHash) =&gt; logTransaction(txHash))<br>    .catch((error) =&gt; <strong><em>console</em></strong>.error);<br>});</pre><p>The full project code, with instructions of how to run the demo application, can be accessed <a href="https://github.com/evandiewald/rto-token">here</a>.</p><h3>Demo</h3><p>Now for a quick demo that demonstrates functionality from the perspectives of both landlord and renter. Before the tenant and home can start earning RTO, our landlord will have to add their property to the smart contract. They can do that by navigating to the “View Listings” tab and filling out a quick form.</p><h4>Role: Landlord</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Q2114RfrlOZOYFXtFo29sQ.png" /><figcaption>Listing a new rental on the RTO network. Image by author.</figcaption></figure><p>Some of these values, like the street address and description, will be stored in our off-chain database. Others, like the down payment (aka earnings threshold) and earnings percentage, will be stored in the smart contract. This page simply prepares the function details, but they will then be asked to explicitly sign the transaction using their Metamask wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*TiQZH7X1eoJb_-jYW_lTSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*s7GoZUrvH3pw3hFRmMGRiw.png" /><figcaption>Signing the transaction with Metamask. Image by author.</figcaption></figure><p>Once the asynchronously-executed transaction is approved, we can view our fancy new listing, along with the immutable details read directly from the ledger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Mgu4Y4FvNSKa5qcvbR9vPA.png" /><figcaption>Image by author.</figcaption></figure><p>Now that our home has been added, let’s make a dent in that earnings threshold and start mining some RTO.</p><h4>Role: Renter</h4><p>Clicking the “Connect Wallet” button brings us to a page that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*cIeeuYSMB1a5qC4yEmMl4g.png" /><figcaption>Image by author.</figcaption></figure><p>The bright orange “Connect Metamask” button will open up a prompt from the browser extension that informs us that our application would like to (for now) simply read our wallet address. When we accept, our active ETH address will magically appear in our application page. Let’s go ahead and check our RTO balance for this wallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*C9cJzZSVS9r5lRPMhpvuNw.png" /><figcaption>Image by author.</figcaption></figure><p>Since we haven’t made any rent payments, of course we don’t have any tokens. To do this, we navigate to the “Pay Rent” tab, fill in our payment amount (in ETH), and the ETH address of our landlord.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*dxJPosfdwxOYmnSz9mbV6A.png" /><figcaption>Image by author.</figcaption></figure><p>Again, the actual transaction signing and private key management is decoupled from the application itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gj5-IUk_oKLGVtJ0mO8uJg.gif" /><figcaption>Image by author.</figcaption></figure><p>In this case, our simulated rent payment was 0.01 ETH, or about $20 (maybe it’s more of a tent than a home). Given an earnings percentage of 30%, we should mine about 6–7 RTO for this transaction. Let’s go ahead and check our balance again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*wNW4qYA-SjFACVPNLQOtgQ.png" /><figcaption>Image by author.</figcaption></figure><p>And the same amount has also been applied to the home listing (see Balance Paid):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*w1bf6hzcQqOPbswaGC0AwQ.png" /><figcaption>Image by author.</figcaption></figure><p>Interestingly, like any ERC20 token, we can also view our balance right in Metamask by adding the smart contract address!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*OF1Q1sB8F0M6tJUYUX2wpw.png" /><figcaption>Viewing our RTO balance in Metamask. Image by author.</figcaption></figure><h3>Final Thoughts</h3><p>This application was relatively simple to develop, but it demonstrates some significant concepts. Renters cannot fabricate their RTO balance, or obtain tokens through any other means other than steadily paying rent. Similarly, while landlords have strong incentives to participate in this network (motivated renters, guaranteed pre-sale earnings, no need to engage with centralized property management), their RTO balance is also on public display. Under traditional frameworks, establishing this trustless interaction would require painstaking recordkeeping and the threat of strong consequences to disincentivize fraudulent behavior. But with a robust public blockchain, accessing these benefits is trivial. We hear a lot about “Yield Farming”, leveraged trading, and other complicated DeFi instruments, but the most sustainable applications of cryptocurrencies involve re-thinking how we establish trust in everyday relationships.</p><p>All code is available on <a href="https://github.com/evandiewald/rto-token">Github</a>.</p><h4>References</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3786cf1142" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-an-ethereum-token-to-enable-a-decentralized-rent-to-own-network-cc3786cf1142">Creating an Ethereum Token to Enable a Decentralized Rent-to-Own Network</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CryptoMingle: The World’s First Dating App with a Smart Contract for Height Verification]]></title>
            <link>https://evandiewald.medium.com/cryptomingle-the-worlds-first-dating-app-with-a-smart-contract-for-height-verification-f2bc6117cbd9?source=rss-1faf67ba837e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bc6117cbd9</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Evan Diewald]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 01:04:36 GMT</pubDate>
            <atom:updated>2021-06-06T01:29:46.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eka06iIEeBSWg30Qv9hOSA.png" /></figure><p>Tinder. Bumble. Hinge. Raya. FarmersOnly. In 2021 the landscape for online dating platforms is as crowded as it’s ever been, as dozens of apps compete to carve out their own niche of a multi-billion dollar market by adding new features, improved algorithms, or exclusive access. However, no application has been able to solve one of the <a href="https://onlinelibrary.wiley.com/doi/full/10.1002/9781118540190.wbeic118">most prominent complaints</a> that users have: misrepresentation or falsification in potential suitors’ profiles. In particular, shrewd sub-six footers like myself have long used clever editing and optical illusions to get away with dishonest portrayals of perhaps the most important feature on a young woman’s mind, our true height. That is, until now.</p><p>Introducing <strong>CryptoMingle</strong>, The World’s First Decentralized Dating App with a Smart Contract for Height Verification. (Just want to see the demo and skip the tutorial? Scroll down to the last section)</p><h3>Tutorial</h3><p>Let’s take a look at the full CryptoMingle stack (<a href="https://github.com/evandiewald/cryptomingle">Github</a>) before diving into the tutorial. The key components are:</p><ul><li>An <strong>Ethereum smart contract</strong> that allows trusted entities (like an independent physician or a notary public) to add users’ height data to the blockchain for cryptographic-grade security</li><li>A <strong>PostgreSQL database</strong> for rapid, reliable access to off-chain data, like email addresses and thumbnail links</li><li><strong>Immutable file storage</strong> for profile images via IPFS and Pinata</li><li>A <strong>FastAPI web server </strong>to route it all together</li><li>And a clean <strong>frontend </strong>to visualize our revolutionary platform</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9XN8lXJuKOiiHdpM8RALg.png" /><figcaption>The CryptoMingle Stack</figcaption></figure><p>We’ll walk through the setup for each of these subsystems as well as the Python code that will connect them.</p><h4>Smart Contract</h4><p>We’ll start with what makes our decentralized application…decentralized. When it comes to smart contracts, no one does it better than the World’s Supercomputer. Despite some well-funded new competitors, Ethereum has, by far, the largest developer community of any blockchain platform, a great ecosystem of tools and SDK’s, and robust Testnets to use as a proving ground. I recently wrote a <a href="https://evandiewald.medium.com/using-the-flow-blockchain-to-make-a-decentralized-ticket-exchange-570218687eb">blog about using the Flow blockchain to build a decentralized ticket exchange</a>, and while Flow had excellent documentation and useful features, developing on Ethereum was a breeze in comparison.</p><p>Ethereum smart contracts are written in Solidity, which has its own web-based IDE called <a href="https://remx.ethereum.org/">Remix</a>. As we’ll see here, Remix makes it easy to debug, compile, deploy, and test your smart contracts right from the browser. As an object-oriented language similar to JavaScript &amp; Python, Solidity is actually pretty intuitive. In the spirit of Ethereum’s overall philosophy of aggressive iteration, each new version of Solidity brings new features, but also breaking changes. I ran into a couple issues where certain code fragments that used to work for v0.7.0 needed to be restructured for v0.8.0. Here’s the code for our relatively simple HeightValidation smart contract:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca70bf1e97c314ead7f532ed8f9e39ae/href">https://medium.com/media/ca70bf1e97c314ead7f532ed8f9e39ae/href</a></iframe><p>Like I said, pretty straightforward. We will store a userList array of User struct’s, which include an integer identifier that will relate to metadata in our off-chain database, a height value in inches, and the address of the ETH account that signed the transaction. We use a mapping to index each entry to that user’s ETH address. TheaddUser function requires that only the account that deployed the contract can validate new users’ heights, and two read-only functions, getHeight and getUsers retrieve the relevant data for us. A nice note is that only the addUser function will incur a gas fee.</p><p>I’ll skip over the steps to compile and deploy the contract using Remix and your Metamask wallet, which are described <a href="https://medium.com/swlh/deploy-smart-contracts-on-ropsten-testnet-through-ethereum-remix-233cd1494b4b">here</a>. After compiling, copy the contract ABI from Remix and paste it in a file called contract_abi.json. Once deployed to the Ropsten testnet, we can even view our contract and all associated transactions on <a href="https://ropsten.etherscan.io/address/0x251f531B769DfF5efF47152899f14b14d78c7d0f">Etherscan</a>!</p><p>We will interface with our contract using the Web3 library for Python. This is another example of where Ethereum’s impressive developer resources can be leveraged to our advantage. Rather than running our own API node, we’ll let <a href="https://infura.io/">Infura</a> host it for us for free (up to 100,000 requests/day, at least). Create a new project and save your endpoint URL, which looks like</p><p>https://ropsten.infura.io/v3/abc123....</p><p>In transactions.py our Python functions will mirror the contract functions that they represent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c13fba0f9de61f7962fe8b65589ddff/href">https://medium.com/media/2c13fba0f9de61f7962fe8b65589ddff/href</a></iframe><p>The most complex function is add_user because it involves an alteration to the Ethereum (testnet) world state and thus, incurs a gas fee (in fake ETH, in our case). Remember we specified that only the account that deployed the contract has permission to validate users’ heights, so we need to get that same account’s address and private key (I recommend doing this through Metamask). In this way, that account can sign transactions on behalf of others.</p><p>Next, we will set up a relational database to store off-chain user data.</p><h4>Relational Database</h4><p>I stood up a local PostgreSQL connection using <a href="https://www.pgadmin.org/">pgAdmin</a>. We need a table called users with columns for all the relevant metadata you might need for a dating app, like name, age, bio, and URL’s for a profile image (more on this in a moment). The full schema is shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*8WXCzBuw_ReXHSnsd7-CIw.png" /></figure><p>address refers to that user’s ETH address, which is needed for our smart contract. transaction will be the Etherscan URL pointing to the addUser transaction that cryptographically secured your accurately-measured height in the blockchain. Forever.</p><p>There are different ways to connect to SQL databases with Python, but my preference is <a href="https://www.sqlalchemy.org/">SQLAlchemy</a>. It’s much cleaner and more intuitive than writing raw queries with a package like <a href="https://www.psycopg.org/">psycopg</a>. These helper functions and the table schema are defined below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e58fe06bd2804b961ff16074f0f9c6d6/href">https://medium.com/media/e58fe06bd2804b961ff16074f0f9c6d6/href</a></iframe><h4>Pinning to IPFS with Pinata</h4><p>You have a lot of options when it comes to cloud-based file storage for our profile images, but in the spirit of decentralization, CryptoMingle will utilize IPFS and Pinata, a pinning service with a Dropbox-like interface. <a href="https://pinata.cloud/documentation#GettingStarted">Follow these instructions</a> to get a free Pinata account and create an API key. Now, we’ll be able to upload profile images from our application and retrieve their IPFS hash, a unique content-based identifier (as opposed to a path-based identifier like images/profile.jpg, where the underlying content can change without changing the URL). I am going to use the requests library to post image uploads to our Pinata client.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/489c92152cf1df796914d4eb4bc19b8e/href">https://medium.com/media/489c92152cf1df796914d4eb4bc19b8e/href</a></iframe><h4>FastAPI Web Server</h4><p>Now let’s bring all these pieces together. We’ve already created functions to interact with our smart contract, database, and cloud storage, so our API just needs to serve these components to our frontend. I have been using <a href="https://fastapi.tiangolo.com/">FastAPI </a>for Python-based servers because it has built-in support for asynchronous functions and better performance than alternatives like Flask. I’ll also take advantage of features for HTML templates and forms.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33bc001621f17847e2e63aa8f0963fae/href">https://medium.com/media/33bc001621f17847e2e63aa8f0963fae/href</a></iframe><p>It could clearly use some efficiency &amp; error handling improvements, but this will be fine for our needs. Our modest little web app will have a homepage to view listings of all eligible matches and a signup form for new users.</p><h4>Frontend</h4><p>Finally, let’s make this look nice with HTML and <a href="https://getbootstrap.com/">Bootstrap</a> for styling. First is our homepage, which will display matches’ photos alongside their name, age, and bio. By clicking on a user’s height, you are directed to the Etherscan transaction that added their info to the blockchain. We’ll also add a mailto: link so that if you like what you see, you can kick off a conversation via email.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cd248f0f98b28319ca4a449e31ac811/href">https://medium.com/media/4cd248f0f98b28319ca4a449e31ac811/href</a></iframe><p>Last but not least, our signup form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00ea7deca5d2291ca97dfe97e77590e6/href">https://medium.com/media/00ea7deca5d2291ca97dfe97e77590e6/href</a></iframe><p>Now let’s take a look at the final product!</p><h3>Demo</h3><p>Launch the development server locally with uvicorn.</p><p>$ uvicorn main:app --reload</p><p>Then open a browser to localhost:8000. You’ll be greeted with a depressingly empty homepage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LKWanmWaykH_Z4PK1HBQw.png" /></figure><p>Time to add some users! Click on the Sign Up tab in the navbar to bring up the registration form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oI--5p41qBOa6ADOGgFdQ.png" /></figure><p>Once you click submit, you may have to wait a minute or two. Most of this time is waiting while our addUser transaction is submitted, validated, and added to the Ethereum ledger. A nice optimization would be to decouple the transactions from the other steps. If all goes well, you’ll be redirected back to the homepage. Oh nice, it looks like we’ve gotten some other CryptoMinglers in the meantime!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bPykSYCTs39KJ2ZJ3xAlA.png" /></figure><p>And there you have it. A full-stack dApp with all the trimmings.</p><p>Source code on <a href="https://github.com/evandiewald/cryptomingle">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bc6117cbd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>