<?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 Vladimir Halme on Medium]]></title>
        <description><![CDATA[Stories by Vladimir Halme on Medium]]></description>
        <link>https://medium.com/@vhalme?source=rss-4f47f535229c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zN9KuRLRDI573aD0</url>
            <title>Stories by Vladimir Halme on Medium</title>
            <link>https://medium.com/@vhalme?source=rss-4f47f535229c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:46:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vhalme/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[AI Driven Development: Feature code generation]]></title>
            <link>https://medium.com/@vhalme/ai-driven-development-feature-code-generation-c59693c04b0c?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c59693c04b0c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 10:26:16 GMT</pubDate>
            <atom:updated>2024-03-03T10:26:16.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1PrvtNNqxNfcfy-jaXpuQ.png" /></figure><p>In my <a href="https://medium.com/@vhalme/ai-driven-development-hello-world-9315bca272b0">previous article</a> I started to develop the concept of AI driven development in large scale software projects. I asked ChatGPT to suggest me a blueprint for such endeavour and I have followed it by implementing basic tooling for code generation. The AI tooling was one of the points of that blueprint but it is only one of its components and if you would like to get a larger context and the motivation for this project, I would suggest you to refer to the <a href="https://medium.com/@vhalme/ai-driven-development-hello-world-9315bca272b0">previous article</a> in this series.</p><h3>Scaffold AI</h3><p>One of the prequisites of establishing an AI driven development process was developing tooling that allows me to create feature code leveraging AI. I decided to package it as a publicly available library that I can share with all of you and I called it Scaffold AI. The main functions of Scaffold AI are maintaining the context of our project and generating ChatGPT prompts to assist in creating new feature code.</p><h4>Overview</h4><p>A large scale application has many components that implement feature code. In order to instruct ChatGPT to generate the code for each component, we need to specify what the components are and supply the instructions to ChatGPT to generate code for each of them. On a higher level we need to translate feature requirements to the requirements for each application component and ask ChatGPT to interpret these requirements. This means having two levels of AI invocation:</p><ul><li><strong>App component code generation</strong>: Prompting for code generation given a template, parameters and instructions.</li><li><strong>Feature prompts generation</strong>: Prompting for app component generation prompts based on feature parameters.</li></ul><h4>Configuration</h4><p>Maintaining the context assumes having configuration that defines our project structure and metadata necessary to generate ChatGPT prompts that result in output that we can plug into our project to implement new features. We have defined two levels of abstraction needed to implement code generation: <strong>feature</strong> and <strong>app component</strong>. Using JSON format we can define these in the root configuration file <em>index.json</em>:</p><pre>{<br>  &quot;feature&quot;: &quot;app-feature&quot;,<br>  &quot;codegen&quot;: &quot;app-codegen&quot;<br>}</pre><p>The root configuration file simply points to relative locations of configuration code for each of the two levels of our Scaffold AI configuration. In the example above the <strong>feature</strong> key points to the directory where the feature prompts generation configuration resides and <strong>codegen</strong> key to the directory with the instructions for code generation for each application component. We will use <em>index.json</em> as the entrypoint to every configuration level.</p><p><strong>Configuration directory structure</strong>: The root configuration <em>index.json</em> file described above resides in the root of the configuration directory structure. The rest of the directory structure in our example looks like this:</p><pre>├── index.json  # Root configuration file (described above)<br>├── codegen/    # Configuration for individual app components<br>│   ├── index.json  # Code generation configuration file<br>│   ├── backend/              # Application<br>│   │   └── data/             #  component<br>│   │       ├── repository/   # directories<br>│   │       │   ├── sample.sql   # Code sample for AI code generation<br>│   │       │   └── usage.md     # Instructions on code sample usage<br>│   │       └── schema/<br>│   │           ├── sample.sql<br>│   │           └── usage.md        <br>│   └── schema/<br>│       ├── sample.sql<br>│       └── usage.md<br>└── feature/    # Configuration of features<br>    ├── index.json    # Index of features<br>    └── backend.txt   # Prompt template for the &quot;backend&quot; feature </pre><p><strong>Codegen configuration</strong>: Code generation configuration <em>index.json</em> file contains the configuration for the templates for each app component and the usage instructions elaborating on usage of the template to generate the app component code. Let’s say one of the app components involved in implementing the feature code is database migration needed to create a table representing the new feature. Another component would be the Typescript type corresponding to that database entity and another one would be a repository structure implementing basic access functions to the new entity. The codegen configuration on the part pf these components would look like:</p><pre>{<br>  ...<br>  <br>  &quot;schema&quot;: {<br>    &quot;sample&quot;: &quot;schema/sample.sql&quot;,<br>    &quot;usage&quot;: &quot;schema/usage.md&quot;<br>  },<br>  &quot;backend/data/schema&quot;: {<br>    &quot;sample&quot;: &quot;backend/data/schema/sample.ts&quot;,<br>    &quot;usage&quot;: &quot;backend/data/schema/usage.md&quot;<br>  },<br>  &quot;backend/data/repository&quot;: {<br>    &quot;sample&quot;: &quot;backend/data/repository/sample.ts&quot;,<br>    &quot;usage&quot;: &quot;backend/data/repository/usage.md&quot;<br>  }<br><br>  ...<br><br>}</pre><p>The codegen configuration points to the sample files that are used as templates for code generation for each component and the usage instruction files containing any instructions how to interpret the sample file and generate new code based on it.</p><p>In our example we have a <strong><em>schema</em></strong> component that defines the SQL template for creating an entity representing a feature. Let’s say we are using PostgreSQL as our database in this project and our sample file <em>schema/sample.sql</em> could look like:</p><pre>CREATE TABLE IF NOT EXISTS entity_name (<br>  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>  other_entity_id UUID REFERENCES other_entities(id),<br>  name VARCHAR<br>);<br><br>CREATE INDEX IF NOT EXISTS entity_name_other_entity_id_idx ON entity (other_entity_id);<br><br>ALTER TABLE entity OWNER TO another_user;</pre><p>While the instructions for its usage in <em>schema/usage.md</em> could be:</p><pre>- The database is PostgreSQL<br>- Shared access user name is slw_user</pre><p>Assuming <em>slw_user</em> exists in your database setup and used by your application.</p><p>Similarly the configuration for <em>backend/data/schema/sample.ts</em> could be:</p><pre>export type entity_name = {<br>  id?: string<br>  other_entity_id: string<br>  name: string<br>};</pre><p>And its usage instruction in <em>backend/data/schema/usage.md</em></p><pre>- do not use semicolons in the end of line<br>- every entity has optional string id</pre><p>All other configuration items would follow the same pattern by defining a sample file that will be evaluated by ChatGPT to generate new code applying configured instructions and taking user prompt as the feature definition.</p><p><strong>Feature configuration</strong>: Feature configuration is used to construct prompts for code generation of various app components as defined above. Basically, feature configuration is a template containing a collection of prompts invoked to generate feature code utilising codegen configuration discussed above. Available features are indexed by the <em>index.json</em> file that maps features to feature configuration files:</p><pre>{<br>  &quot;backend&quot;: &quot;backend.txt&quot;<br>  ...<br>}</pre><p>Feature configuration file is a txt file that follows format:</p><pre>app/component/identifier: Prompt template<br>...</pre><p>Assuming the app component structure defined above we could have a feature configuration file <em>backend.txt</em> containing instructions like:</p><pre>schema: Create new table representing dogs to a table named dogs with properties name, owner_id (uuid, idexed, references person), age (int)<br>backend/data/schema: Create new entity type for dog to represent a table with properties name, owner_id (string), age (int)<br>backend/data/repository: Create new repository named DogRepository. The columns are name, owner_id, age</pre><p>Each line in the feature configuration file starts with a an app component reference (eg. <em>backend/data/schema</em>) separated by a colon from the prompt template used to generate the code for that app component.</p><h3>Implementation</h3><p>Scaffold AI is basically a tool that manages ChatGPT prompts and metadata as well as maintains the project context in order to produce code with awareness of the surrounding project and in consistent style.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*yS84WNre8t1Y5tCb9iUkJw.png" /></figure><p>The input to Scaffold AI contains the definition of a feature that typically consists of a description of an entity such as its name and its properties. First, Scaffold AI generates a prompt for ChatGPT that incorporates the user given feature definition and asks to generate prompts that can be used subsequently to request ChatGPT to generate code content for different app components. This first prompt is constructed based on the feature definition template that contains sample prompts for each app component involved in the feature. Scaffold AI then executes the generated prompts against ChatGPT to get the desired code for the app components.</p><h3>Usage</h3><p>In the first chapter of this article we have covered configuration of Scaffold AI. Once the configuration is in place we can run the tool from the command line to generate the code for all app components defined in the configuration.</p><p>I have a real software development project that I’m working on: <a href="https://medium.com/@vhalme/solarwind-galactic-metaverse-89a4f80d7ea9">Solwarwind — Galactic Metaverse</a>. It’s a metaverse with gaming features set in our home galaxy and it has such features as stars and space ships. I would like to apply Scaffold AI in the development of this project and I’m going to try to generate a feature for this project. In fact the templates I have set up in this article are designed for this particular project. But now we will try Scaffold AI in real life usage expecting usable code we could plug in to our application. Exciting, let’s try!</p><pre>bun ../scaffold-ai/index.ts solarwind-scaffold feature backend \<br>  &quot;The feature is Npc character, the term in code should be Npc. \<br>   It has properties name (string), owner_id (uuid, indexed, references user), \<br>   ship_id (uuid, indexed, references ships), \<br>   compartment_id (uuid, references ship_compartments), \<br>   health (double), status (string), level (int)&quot;</pre><p>The aim of the prompt should be self explanatory. But how is the result? Well, it’s not perfect. There are some things that I needed to fix manualky and that I will need to clarify in my templates or template instructions later.</p><ul><li>The name of the table started with capital letter: “Npcs”</li><li>The reference to users table in the schema was in singular: <br><em>owner_id UUID REFERENCES </em><strong><em>user</em></strong><em>(id)</em></li><li>Field names in the entity type I use in repository level were converted to camel case opposed to desired snake case</li><li>Field (column) names in the repository were also in camelCase opposed to desired snake case</li><li>There was one “Object is possibly null” Typescript error</li></ul><h3>Conclusion</h3><p>All above errors were easily fixed by adding more explicit template usage instructions and a couple of minimal code fixes. The result of code generation was 6 files or partial file contexts to the following app components:</p><ul><li>Database schema</li><li>Database entity Typescript type</li><li>Repository code</li><li>Model type</li><li>Service code</li><li>Route handling code</li></ul><p>This single prompt generated the total of about 250 lines of code (including empty lines). The code was generated to standard output, so it took some time to copy-paste it manually in IDE but I think the next feature I will add to Scaffold AI will be automatic merging of the code to existing code base. In any case the experiment was a success and using just this simple tool would definitely turbocharge my development process.</p><h3>Lessons learned</h3><p>Generated code components have references to each other and some of their properties (such as field name format — snake or camel case) should be propagated in code generation prompts for individual components.</p><p>Generating code strictly from the top (feature description) to bottom (component code generation) doesn’t account for horizontal dependency of component properties. In the next iteration of Scaffold AI I plan to design how to maintain some kind of context that can be used to make ChatGPT aware of relations between components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c59693c04b0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Driven Development: Hello world!]]></title>
            <link>https://medium.com/@vhalme/ai-driven-development-hello-world-9315bca272b0?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9315bca272b0</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Sat, 02 Dec 2023 17:07:40 GMT</pubDate>
            <atom:updated>2023-12-02T17:44:14.279Z</atom:updated>
            <content:encoded><![CDATA[<p>After having used ChatGPT to generate tiny utility programs and using it for assistance in solving isolated software development problems, I wanted to delve deeper into exploring its potential in assisting software development on a larger scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7_zB2L6yK9z5c6XFeLa6g.png" /></figure><p>I got an idea for a product that I want to develop the software for. I have experience of development large scale personal software projects and the problem with them has been that they grow too large for me to handle the software development on my own. The prospect of just creating the prototype for my new product is daunting understanding the hours that will go into coding it the traditional way. There’s no way I’m going through that grind again.</p><h3>Redefining objectives</h3><p>This time I will attempt a different approach and set my objectives differently. In the past my objective was to develop a prototype of the product and keep building it up while developing the business. I still haven’t been able to launch the business using this approach because even though with each new attempt I scaled down my software development input and put more effort into the business, the software development part was still always too demanding to perform alongside business development.</p><p>This time around I have a different set of objectives.</p><ol><li>Learn large scale AI driven development in-depth</li><li>Develop scalable AI tooling for a software project</li><li>Leverage developed AI tools and methodology to prototype the product rapidly</li><li>Extend the AI driven methodology to support business development for the product</li></ol><h3>Enter ChatGPT</h3><p>I started with defining my intention on the high level.</p><blockquote>I’d like to start developing a new software product and create application code for it utilising ChatGPT in the development process from the very beginning. First of all I want to establish AI tooling for my project. The purpose of the tools is to interact with ChatGPT via API to generate code to my application given feature requirements and to store the context of my application in such way ChatGPT would be aware of the entire code base and my development goals. I want to develop these tools using Typescript and Bun runtime.</blockquote><p>The response was an overview of subjects such as <strong>Project Setup</strong>, <strong>ChatGPT Integration</strong>, <strong>Feature Requirement Processing</strong> and <strong>Code Generation And Integration</strong>. I can use each of these subjects when I start drilling down to implementation of the project.</p><p>Context scalability was a special concern that I wanted to address from the beginning as managing larger context has been something where I’ve experienced ChatGPT to fall short.</p><blockquote>The project code base including tests, configuration and infrastructure code will eventually encompass numerous git repositories and web services. It may eventually comprise hundreds or even thousands of files. Is there a way to make ChatGPT aware of the entirety of this context using API?</blockquote><p>ChatGPT recognized its inability to support direct awareness of an extensive code base and offered a set of solutions to achieve my goal based on <strong>segmentation and management of context data</strong> as well as <strong>scalable workflow solutions</strong>.</p><blockquote>Let’s start by designing the project structure. I want to use Bun runtime and Typescript as the primary development language in a multi repository setup. The first module of the project is AI tooling enabling AI driven development referenced in my initial message of this conversation. Suggest me the project structure.</blockquote><p>I got a workable suggestion for a project structure that was close to what I would have created myself. I created a directory for the AI tooling module and went on to initialize the Bun project for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*-Lu486pFbL0xKibuU-d2IQ.png" /></figure><blockquote>Let’s start with the AI tooling module. Give me a step by step guide to initialize the project and the repository.</blockquote><p>Following these copy-paste instructions I had my initial project setup commited to a local Git repository. I requested to change the testing runtime from jest to Bun’s native tests, created my first test and ran it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*E2FJem_ZpPq5eIXrb4Ugkw.png" /></figure><h3>Next chapter</h3><p>In this chapter we defined our problem and stated our intention. We used ChatGPT to outline our project and set up some initial scaffolding for it. In the next chapter we will move on to design and implementation of some essential functionality of AI tooling. I have a feeling it’s going to be a very interesting chapter, and I hope to see you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9315bca272b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solarwind: Galactic Metaverse]]></title>
            <link>https://medium.com/@vhalme/solarwind-galactic-metaverse-89a4f80d7ea9?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/89a4f80d7ea9</guid>
            <category><![CDATA[interstellar-travel]]></category>
            <category><![CDATA[metaverse]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[science-fiction]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 11:11:22 GMT</pubDate>
            <atom:updated>2023-06-30T16:35:03.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94twd5AaZ3qot35AdQSXNQ.png" /></figure><p>I lived in Copenhagen for about half a year last winter. The sky was exceptionally clear and I started to look up in the sky on my evening walks with our dog, getting drawn into the starry void above me. I learned how to find stars in their constellations and started to learn about each star’s characteristics. I’ve been a fan of space and science as long as I remember and have read a lot of science fiction but that winter it was like a made a physical connection with that great ocean of space and I discovered the amazing diversity and magnificence of the worlds that twinkle in our night sky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfN6RoNyQNjTr0U_dvZ6bw.png" /><figcaption>It is me with the dog and a photo of Sirius taken with my phone camera in the night sky of Copenhagen.</figcaption></figure><p>Solarwind metaverse was the way for me to reach out to those stars. I will never be an astronaut but I am a software developer and the best thing in my profession is the ability to build bridges between physical world around us an the world of reason and imagination within our mind! I developed Solarwind metaverse as a galactic playground set in our home galaxy that models physical properties of the space and stars around us as well as laws of physics. It is initially a very rough approximation and laws of physics have to be bent a little to make interaction with the metaverse an engaging experience but the plan is to add details, complexity and realism to the extent that technology will allow.</p><blockquote><strong>I developed Solarwind metaverse as a galactic playground set in our home galaxy that models physical properties of the space and stars around us as well as laws of physics.</strong></blockquote><p>Solarwind metaverse runs largely on blockchain because I think it is the medium that corresponds well to the idea of space without central authority, being governed by immutable laws of physics and being equally transparent and impartial to all human actors.</p><p>As a participant in the Solarwind metaverse, you are given your first space ship that you can use to harvest Sun’s energy (Solarwind, distributed as a utility token SLW). You can then use this energy to travel to other stars, build new ships or engage in combat. The driving force of the metaverse is space exploration. The more distant unexplored stars are, the more energy it takes to reach them and acquisition of this energy requires engaging in the economy of the metaverse and in interaction with other participants.</p><h4>Stars</h4><p>Each star is a unique world ranging from brown dwarves to blue giants. The star is the source of energy (Solwarwind, SLW). Your ships are harvesting the star’s energy while they are in the star’s orbit. Physical properties of the star such as luminosity, mass, diameter and spectral type are factors in your harvesting and other activities in that world. For example more luminous stars give a chance to harvest energy at an accelerated rate but require more maintenance and are less suited for other orbital activities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F665NcQM5Yi80APkwQPYBA.png" /><figcaption>Most metaverse activity takes place in stars’ orbits. Each star is a world that features its own economy and community.</figcaption></figure><p>Each star has a pre-minted NFT corresponding to it and its ownership makes you the owner of that world in the metaverse. All you need to do to claim your own star is to be the first one to reach it! Our closest neighbour is Proxima Centauri but due it its proximity chances are that someone has already claimed it, so you will need to look further out! As an owner of a star you can develop this world by managing construction operations of permanent structures, administering and building the world’s community and regulating economy of the world that includes the ability to collect tax from the energy (Solarwind, SLW) collected from the star by other participants.</p><p>When the star has been claimed by someone, it is still possible to acquire it just buy buying the NFT from the current owner!</p><h4>Ships</h4><p>Ships are the main medium of interaction with the universe. They can be built, sent to other worlds, used in harvesting energy and in battle. Building and operating a ship requires energy (Solarwind, SLW).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjKSpmd_yqpYdpjlreWmxg.png" /><figcaption>Another central activity in the metaverse is management the fleet of ships. Ships are the vessels that move you around and let you interact with the universe and other players.</figcaption></figure><p>Ships can be developed by modifying their visual appearance, extending their hull, adding equipment and managing the ship’s crew. The ships also gain XP during their lifetime and the ships are NFTs that can be traded on the market.</p><h4>Space exploration</h4><p>The ultimate goal of metaverse activities is space exploration. After the discovery of our local galactic bubble and establishing colonies in such neighbouring worlds as the Centauri and Sirius systems, Barnard’s star and Wolf 359, we have the economy in place that puts even more distant worlds within our reach such as the glorious Betelgeuse that is on the verge of going supernova!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9m5qfL8Ljlok1cyIKIRFCg.png" /><figcaption>Discover stars in the vicinity of your explored space and send your ships to push the frontiers or to do business.</figcaption></figure><p>The further we reach out, the more energy we need and our growth into a truly galactic civilization is fuelled by our metaverse activities — competing and collaborating with each other, developing our colonized worlds, building economy and perfecting our ships.</p><h3>Join me! Help me!</h3><p>The <a href="https://solarwindmetaverse.com/">Solarwind MVP</a> (<a href="https://solarwindmetaverse.com/">https://solarwindmetaverse.com</a>) running on Polygon Mumbai Testnet is live. At the moment it is at the Proof-of-Concept level that is intended as the starting point for the project.</p><h3>I’m looking for like minded people to join me in development of Solarwind into the vision sketched out in this article.</h3><p>All contacts and feedback are eagerly welcome! Join the community of pilot users and become a founding member! Do you think you can contribute in the field of business development, game design or game economy development, community building, software development, art? Or maybe you know someone whose contact you would like to share? Please, please, contact me to discuss cooperation! I’m reachable by e-mail contact@solarwindmetaverse.io, <a href="https://discord.gg/3wnNhCHW">Solarwind Discord server</a> or <a href="https://www.linkedin.com/in/vladimir-halme-7ba2b55/">my LinkedIn profile</a>. Or just share your opinion and feedback in the comments section. Like, share, get the word out! Let’s do it! To the stars!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89a4f80d7ea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An architecture for a DEX trading app]]></title>
            <link>https://medium.com/@vhalme/an-architecture-for-a-dex-trading-app-b277da55bcf?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b277da55bcf</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[decentralized-finance]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[decentralized-exchange]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 16:55:23 GMT</pubDate>
            <atom:updated>2023-01-23T19:33:08.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcjLNtIaeAw3EhpAeOyEuA.png" /></figure><p>In a couple of previous articles we concentrated on creating the most essential core functionality necessary for our app to work:</p><p><a href="https://medium.com/@vhalme/getting-started-with-dex-in-node-js-5d358412f13?source=your_stories_page-------------------------------------">Getting started with DEX in Node.js</a>: Establishing the basics of using DEX platforms and creating a prototype able to read price quotes for a given pair.</p><p><a href="https://medium.com/p/9a0a51fe1360/edit?source=your_stories_page-------------------------------------">Executing a trade in Node.js using UniSwap V3 protocol</a>: Expanding the functionality of our prototype to perform trades and organising the code for the context of a more complex app.</p><p>In this article we will step up in a design level and consider the architecture we need to put in place to facilitate development of our product. At this point we need to define some requirements and come up with a draft of the architecture that should enable them.</p><h3>Functional requirements</h3><p>Our app needs to monitor all or a subset of liquidity pools on a DEX and display the price development of any selected pair on a chart. There is a basic hard coded trading strategy in place and its indicators are displayed on the chart.</p><h4>Data collection</h4><p>Our app should collect price data for all or a subset of traded pairs at regular intervals and save them as time series data. This data should be possible to display in the candle stick format by a charting library.</p><h4>Data display</h4><p>The user should be able to see price development in the candle stick format and indicators such as moving averages and Buy/Sell signals on the same chart.</p><h4>Indicators</h4><p>The app should produce a couple of indicators generated from the price history. The indicators should be accessible as code functions.</p><h4>Strategy execution</h4><p>A trading strategy is defined (hard coded at this point) that takes the price data and the indicators as input and produces Buy/Sell signals as output.</p><h3>Architecture design</h3><p>We can design the architecture based on the requirements we identified above. This is going to be a Node.js app with a web frontend for data display and user interaction. Let’s first make a rough architectural draft of an MVP that will give us a general idea of the processes and components that will be involved in the implementation of the app.</p><h4>Backend</h4><p>The two central backend processes of the app will be data collection and the web server. The data is polled from a DEX and stored locally in a JSON file (we will change this method later when we continue to develop our project). Web server provides an API for fetching the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*IJdgzEkneyf4KYKJlnW70Q.png" /></figure><p>Data collection triggers execution of the strategy which uses the indicator library and creates new data points as trade signals. These signals will be fetched by the frontend in subsequent requests. The strategy component also saved indicator values in the data storage. The strategy runner in the MVP is simply a block of Javascript code that executes whenever new price input is received but in the future we can consider moving some parts of this functionality to smart contracts.</p><p>The web app container implements routing of API calls which in turn use services that utilise a data access layer that lets our app to query time series data. We’ll go with REST API for the MVP and consider GraphQL at a later stage of development.</p><h4>Frontend</h4><p>The frontend features a TradingView chart that polls our backend API. It displays the price history, indicators used by our strategy and trade signals. The data connector component runs in a loop and supplies the updated price, indicator and signal data to the instance of the TradingView chart initialised at page load.</p><p>There’s no custom interaction in the MVP, interaction features will be designed and implemented incrementally. The TradingView chart itself though features considerable degree of interactivity and together with signal data generated by our backend already provides some value which the point of an MVP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*qLlEAmfTBiKzfshSaPu6pw.png" /></figure><p>This is an architecture for a very limited MVP which will be the first building block of our trading app. We will expand the functionality step by step and I will document the process in each step. As always, I’m grateful for any feedback from my readers about any errors I might have made or essential points I have omitted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b277da55bcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Executing a trade in Node.js using UniSwap V3 protocol]]></title>
            <link>https://medium.com/@vhalme/executing-a-trade-in-node-js-using-uniswap-v3-protocol-9a0a51fe1360?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a0a51fe1360</guid>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Mon, 16 Jan 2023 08:01:50 GMT</pubDate>
            <atom:updated>2023-01-16T08:01:50.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4P9n4R50HzpKVvT-sDfV0g.png" /></figure><p>In the previous article <a href="https://medium.com/@vhalme/getting-started-with-dex-in-node-js-5d358412f13">Getting started with DEX in Node.js</a> we established some basics about decentralized exchanges (DEX) and created a simple app that interacted with the UniSwap DEX to get a price of a token in a pair. Now we will build upon that and execute a trade that exchanges one of our tokens to another. We will also modularize our code to provide a foundation for the growth of complexity of our application.</p><h3>Initializing a DEX wallet</h3><p>First of all we will put the code for creating a wallet into its own function that takes the blockchain network JSON RPC URL as an argument to be able to select the blockchain of our choice. We will use the Polygon blockchain for our development as it is faster and cheaper than Ethereum.</p><p>Let’s create a <em>dexWallet.ts</em> file in our project with the implementation of our wallet initializer:</p><pre>import { ethers, BigNumber } from &#39;ethers&#39;<br><br>export interface DexWallet {<br>    wallet: ethers.Wallet<br>    walletAddress: string<br>    walletBalance: BigNumber,<br>    providerGasPrice: BigNumber<br>}<br><br>export const initializeWallet = async (network?: string): Promise&lt;DexWallet&gt; =&gt; {<br>    <br>    const { PRIVATE_KEY } = process.env<br><br>    if (!PRIVATE_KEY) {<br>        throw new Error(&#39;Private key missing from env variables&#39;)<br>    }<br><br>    const provider = network ?<br>        // Connect to the user pprovided network<br>        new ethers.providers.JsonRpcProvider(network) :<br>        // Connect to Ethereum mainnet<br>        ethers.getDefaultProvider()<br><br>    // Sign the transaction with the contract owner&#39;s private key<br>    const wallet = new ethers.Wallet(PRIVATE_KEY, provider);<br><br>    const walletAddress = await wallet.getAddress()<br>    const walletBalance = await wallet.getBalance()<br><br>    const providerGasPrice = await provider.getGasPrice()<br><br>    return {<br>        wallet,<br>        walletAddress,<br>        walletBalance,<br>        providerGasPrice<br>    }<br><br>}</pre><h3>Calling a transactional contract method</h3><p>In the <a href="https://medium.com/@vhalme/getting-started-with-dex-in-node-js-5d358412f13">previous article</a> the contract methods we called were read-only and did not require gas to execute. To execute a trade we will need to call some transactional methods that will change the state of the contract and generate transactions that will require a gas fee to be validated. There are a couple of steps involved here, so let’s create a function that performs them and put it in the <em>contractUtils.ts</em> file.</p><pre>import { BigNumber, Contract } from &#39;ethers&#39;<br><br>export async function callContractMethod(contract: Contract, method: string, inputs: any[], gasPrice: BigNumber) {<br><br>    console.log(`${method}(${inputs})`)<br>    <br>    // The default gas limit will be used if gas estimation fails<br>    let gasLimit = BigNumber.from(500000)<br><br>    try {<br>        const gasEstimate: BigNumber = await contract.estimateGas[method](...inputs)<br>        // Double the estimate to make sure the limit is high enough<br>        const gasLimit = gasEstimate.mul(2)<br>        console.log(&#39;Gas estimate:&#39;, gasEstimate.toBigInt())<br>        console.log(&#39;   Gas limit:&#39;, gasLimit.toBigInt())<br>    } catch (error) {<br>        console.log(&#39;Default gas limit:&#39;, gasLimit.toBigInt())<br>    }<br><br>    /**<br>     * Send the transaction to the contract with gasPrice and gasLimit parameters that<br>     * that ensure the successful completion of our transaction.<br>     */<br>    const txResponse = await contract[method](...inputs, { gasPrice, gasLimit })<br>    console.log(&#39;Done! Tx Hash:&#39;, txResponse.hash)<br>    return txResponse<br><br>}</pre><p>This method uses a <em>gasPrice</em> argument that can be adjusted in order to increase the likelihood of our transaction being included in the next block (ie. faster processing). I have also noticed that using the gas price from the provider is sometimes not enough to execute a swap transaction on UniSwap V3 SwapRouter. Gas limit is doubled from the estimate to accomodate for transactions sent with higher <em>gasPrice</em> argument. In theory this allows for the <em>gasPrice</em> argument to also be double the one from provider.</p><p>My understanding of gas management is limited though and if you find errors in my assumptions or can suggest more economic ways to manage gas without sacrificing reliability, I’d love to hear about it in the comments and update the article.</p><h3>Executing a swap</h3><p>Now we have all the tools we need to work with contracts, so let’s put them to work and execute some swaps! Let’s create a <em>swap.ts</em> file in the <em>uniswap</em> folder and define a <em>swap</em> function that performs a UniSwap V3 swap.</p><p>First we’ll import the tools we created earlier:</p><pre>import { BigNumber, Contract } from &#39;ethers&#39;<br>import { DexWallet } from &#39;../dexWallet&#39;<br>import { callContractMethod } from &#39;../contractUtils&#39;</pre><p>We will use three contracts for this operation, two of which share the same ABI. The shared ABI is for the token contracts and it can be found on Polygonscan the same way we extracted ABI from Etherscan in the <a href="https://medium.com/@vhalme/getting-started-with-dex-in-node-js-5d358412f13">previous article</a>. Let’s say we want to swap between USDC and WETH tokens on Polygon blockchain. Their contract addresses are</p><ul><li>USDC: <a href="https://polygonscan.com/token/0x2791bca1f2de4661ed88a30c99a7a9449aa84174">0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174</a></li><li>WETH: <a href="https://polygonscan.com/token/0x7ceb23fd6bc0add59e62ac25578270cff1b9f619">0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619</a></li></ul><p>We’ll copy the ERC20 token contract ABI from either of them and save it as <em>uniswap/contracts/ERC20.json</em>.</p><p>Another contract we will need is <a href="https://docs.uniswap.org/contracts/v3/reference/periphery/interfaces/ISwapRouter">UniSwap V3 SwapRouter</a> and its address is <a href="https://polygonscan.com/address/0xe592427a0aece92de3edee1f18e0157c05861564">0xE592427A0AEce92De3Edee1F18E0157C05861564</a>. We will save its ABI as <em>uniswap/contracts/SwapRouter.json</em> and import both files.</p><pre>import erc20Abi from &#39;./contracts/ERC20.json&#39;<br>import swapRouterAbi from &#39;./contracts/SwapRouter.json&#39;</pre><p>We will create a function that takes three arguments:</p><ul><li>dexWallet: An instance of a DexWallet we defined earlier</li><li>pair: An array of two token contract addresses</li><li>(reverse: Optional boolean flag if we want to perform the swap in the opposite direction)</li></ul><p>Let’s first take a look at the entire function and then explain its less obvious content section by section.</p><pre>export async function swap(dexWallet: DexWallet, pair: [string, string], reverse?: boolean) {<br><br>    const {<br>        wallet,<br>        walletAddress,<br>        walletBalance,<br>        providerGasPrice<br>    } = dexWallet<br><br>    console.log(walletAddress + &#39;:&#39;, walletBalance.toBigInt())<br><br>    const tokenAAddress = reverse ? pair[1] : pair[0]<br>    const tokenBAddress = reverse ? pair[0] : pair[1]<br>    const tokenAContract = new Contract(tokenAAddress, erc20Abi, wallet)<br>    const tokenBContract = new Contract(tokenBAddress, erc20Abi, wallet)<br><br>    const tokenABalance: BigNumber = await tokenAContract.balanceOf(walletAddress)<br>    const tokenBBalance: BigNumber = await tokenBContract.balanceOf(walletAddress)<br>    <br>    console.log(&#39;Token A&#39;, tokenABalance.toBigInt(), &#39;Token B:&#39;, tokenBBalance.toBigInt())<br><br>    const swapRouterAddress = &#39;0xE592427A0AEce92De3Edee1F18E0157C05861564&#39;<br>    const swapRouterContract = new Contract(swapRouterAddress, swapRouterAbi, wallet)<br>    <br>    console.log(&#39;Provider gas price:&#39;, providerGasPrice.toBigInt())<br>    const gasPrice: BigNumber = providerGasPrice.mul(12).div(10)<br>    console.log(&#39;  Actual gas price:&#39;, gasPrice.toBigInt())<br>    <br>    const allowance: BigNumber = await tokenAContract.allowance(walletAddress, swapRouterAddress)<br>    console.log(&#39;Token A spenditure allowance:&#39;, allowance.toBigInt())<br><br>    if (allowance.lt(tokenABalance)) {<br>        await callContractMethod(tokenAContract, &#39;approve&#39;, [swapRouterAddress, tokenABalance], gasPrice)<br>        console.log(`Spending of ${tokenABalance.toBigInt()} approved.`)<br>    }<br><br>    const swapDeadline = Math.floor((Date.now() / 1000) + (60 * 60))<br>    const swapTxInputs = [<br>        tokenAAddress,<br>        tokenBAddress,<br>        BigNumber.from(3000),<br>        walletAddress,<br>        BigNumber.from(swapDeadline),<br>        tokenABalance,<br>        BigNumber.from(0),<br>        BigNumber.from(0)<br>    ]<br><br>    const swapTxResponse = await callContractMethod(swapRouterContract, &#39;exactInputSingle&#39;, [swapTxInputs], gasPrice)<br>    <br>    return swapTxResponse<br><br>}</pre><h4>Token balances</h4><p>Token contracts have a <em>balanceOf</em> method that takes a wallet address as an input and returns the balance of the token in that wallet address. We will need these balances to know how much spending we need to allow and how much we can swap.</p><h4>Gas price</h4><p>Gas price is set by taking provider gas price and multiplying it by 1.2. I found this price to be enough to execute the swap reliably.</p><h4>Allowance and approval</h4><p>In order for a contract to handle our funds, we have to approve their spending. These methods are available on the token contract and what we do here is:</p><ol><li>Check how much of token A the <em>SwapRouter</em> contract is allowed to spend</li><li>Check if the the spending limit (allowance) is less than the token balance</li><li>If we have more to spend than is allowed, approve the <em>SwapRouter</em> contract to spend our entire Token A balance.</li></ol><p>WARNING! You should have raised your eyebrows here. This code indeed will swap your entire balance, so use with care at your own risk and responsibility.</p><h4>Swap execution</h4><p>Finally, we define the inputs for the <em>exactInputSingle</em> method of the SwapRouter contract. To find out more about that contract, you may refer to <a href="https://docs.uniswap.org/contracts/v3/reference/periphery/interfaces/ISwapRouter">ISwapRouter Interface documentation</a>. The <em>exactInputSingle</em> method and its params are as follows:</p><pre>struct ExactInputSingleParams {<br>    address tokenIn;<br>    address tokenOut;<br>    uint24 fee;<br>    address recipient;<br>    uint256 deadline;<br>    uint256 amountIn;<br>    uint256 amountOutMinimum;<br>    uint160 sqrtPriceLimitX96;<br>}<br><br>function exactInputSingle(<br>    struct ISwapRouter.ExactInputSingleParams params<br>) external returns (</pre><h3>Test run</h3><p>The last thing to do is put everything together and call the <em>swap</em> function. I run my code from the <em>index.ts</em> file that looks like this:</p><pre>import { swap } from &#39;./uniswap/swap&#39;<br>import { promisify } from &#39;util&#39;<br>import { initializeWallet } from &#39;./dexWallet&#39;;<br><br>const main = promisify(async () =&gt; {<br>    const dexWallet = await initializeWallet(&#39;https://polygon-rpc.com/&#39;)<br>    const swapResult = await swap(<br>        dexWallet,<br>        [<br>            &#39;0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174&#39;, // USDC<br>            &#39;0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619&#39;  // WETH<br>        ]<br>    )<br>  });<br><br>main().then(() =&gt; {<br>    console.log(&#39;Async operation completed&#39;)<br>});</pre><p>The <em>swap</em> function returns transaction result (assigned to <em>swapResult</em> here) which is an object that has a <em>hash</em> field. This is your transaction hash and can be searched on Polygonscan to track the state of your transaction.</p><pre>&gt; dex-bot@1.0.0 start<br>&gt; ts-node src/index.ts<br><br>0x1802Ca89229234229B0309EEe0D98aba5fC166fa: 185346442497869275n<br>Token A 440274n Token B: 0n<br>Provider gas price: 69898332715n<br>  Actual gas price: 83877999258n<br>Token A spenditure allowance: 0n<br>approve(0xE592427A0AEce92De3Edee1F18E0157C05861564,440274)<br>Gas estimate: 65444n<br>   Gas limit: 130888n<br>Done! Tx Hash: 0x81708defaca7ef9ddca9f069ee3af9cedbb075dfacda3707edba2cea402f20c1<br>Spending of 440274 approved.<br>exactInputSingle(0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619,0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174,3000,0xb648Cfb260e50aFc8751A8342D639201F3712839,1673621493,314012800476050,0,0)<br>Gas estimate: 147263n<br>   Gas limit: 294526n<br>Done! Tx Hash: 0xd69bcd152cbe9f319b2ade6a5f124901985bfd52f7e7833a6f8927da3614a939</pre><p>By this point your entire USDC balance should be exchanged for WETH. I think it was a good trade. HODL!</p><p>And as always all of the code covered in the article is availabe in my <a href="https://github.com/vhalme/dex-bot">DEX-BOT GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a0a51fe1360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with DEX in Node.js]]></title>
            <link>https://medium.com/@vhalme/getting-started-with-dex-in-node-js-5d358412f13?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d358412f13</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 16:05:21 GMT</pubDate>
            <atom:updated>2023-01-12T20:02:28.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Q5_OIyfm0xTuyfPj6s4ww.png" /></figure><p>My goal is to create a trading bot that will scout decentralized exchanges (DEX) for buying and selling opportunities using AI and make me a millionaire… no, at least a billionaire! It’s a nice thing to dream about but there’s a lot of work ahead to get there since I have only just started. I plan to share my entire journey on Medium, so I invite you, my reader, to come along for a ride and learn together with me!</p><p>If we think about functional requirements for such trading bot, I figured that there are two most essential and basic functions that it must perform and that I can kick off my project with.</p><ul><li>Getting a price quote</li><li>Making a trade (buy, sell, swap - depending on the context)</li></ul><p>Next we need to choose the DEX to trade on. I chose <a href="https://uniswap.org/">UniSwap</a> because it is among the largest ones by the amount of liquidity and it provides well maintained tools and documentation for developers.</p><p>So, the starting point of our project will be a simple app prototype that gets price quotes for a chosen token pair.</p><h3>Interacting with a DEX</h3><p>Because DEX runs on the blockchain, we interact with smart contracts deployed there. To do that we will use the well maintained and capable <a href="https://docs.ethers.org/v5/">ethers</a> Node.js library.</p><p>Before we can interact with a contract, we need to connect to the blockchain and provide our credentials to be able to sign transactions.</p><pre>import { ethers } from &#39;ethers&#39;<br><br>// Connect to the BSC mainnet<br>const provider = ethers.getDefaultProvider();<br><br>// Set your private key, eg. by reading it from an environment variable<br>const { PRIVATE_KEY } = process.env<br><br>// Sign the transaction with the contract owner&#39;s private key<br>const wallet = new ethers.Wallet(PRIVATE_KEY, provider);<br><br>const walletAddress = await wallet.getAddress()<br>const walletBalance = await wallet.getBalance()<br><br>console.log(walletAddress + &#39;:&#39;, walletBalance.toBigInt())</pre><p>Voilà! We connected to the blockchain and interacted with it by reading our wallet balance. Getting your private key depends on your wallet, but if you are using Metamask, you can get it by opening the Account options menu and selecting <em>Account details</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*5e0bwfqQJVTfQJZO4S-pMQ.png" /></figure><p>In the next menu choose <em>Export private key</em> and copy it. Be very careful with keeping it safe. I put mine in an environment variable and read it with</p><pre>const { PRIVATE_KEY } = process.env</pre><p>But how do we get a price quote for a token pair? We need to interact with a DEX contract deployed on the blockchain. To interact with a contract using ethers library, we need</p><ul><li>Contract address</li><li>Contract ABI</li></ul><p>Contract ABI is like a schema for the contract and it can be described in JSON format. Contract address is the actual blockchain address where the contract is deployed.</p><p>UniSwap actively develops its platform and the latest version of their protocol is V3. <a href="https://docs.uniswap.org/contracts/v3/overview">UniSwap V3 documentation</a> has very good description of their contracts and there’s also a <a href="https://docs.uniswap.org/contracts/v3/reference/deployments">list of deployment addresses</a> where we can find the first contract we need. It is UniswapV3Factory and its address is <a href="https://etherscan.io/address/0x1f98431c8ad98523631ae4a59f267346ea31f984">0x1F98431c8aD98523631AE4a59f267346ea31F984</a>.</p><p>In <a href="https://etherscan.io/address/0x1f98431c8ad98523631ae4a59f267346ea31f984">Etherscan</a> at the bottom of the page there is a <em>Contract</em> tab where we can find the contract’s source code and the ABI in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_bKdLS1brMSnS5yg7SQbA.png" /></figure><p>The ABI is in the bottom of the page. We will need it in our project, so let’s copy and paste it into a JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEE_yliwylNi80GMpHyBxw.png" /></figure><p>We’ll save it in a <em>contracts</em> folder as <em>UniswapV3Factory.json</em> and import it.</p><pre>import uniswapV3FactoryAbi from &#39;./contracts/UniswapV3Factory.json&#39;</pre><p>Now we can create an <em>ethers</em> contract instance using this ABI and the wallet we created earlier:</p><pre>const uniswapV3FactoryAddress = &#39;0x1F98431c8aD98523631AE4a59f267346ea31F984&#39;<br>const factoryContract = new ethers.Contract(uniswapV3FactoryAddress, uniswapV3FactoryAbi, wallet)</pre><p>We can not get the price quote directly from this contract though. In UniSwap V3 protocol we need to use this contract to get us the contract address of the pool that provides liquidity for a pair of tokens. That contract, in turn, has a method that will give us the data needed to calculate the token price.</p><p>So let’s get the pool address of two tokens using the contract’s <em>getPool</em> method:</p><pre>  function getPool(<br>    address tokenA,<br>    address tokenB,<br>    uint24 fee<br>  ) external view returns (address pool)</pre><p>We’ll use USDC and WETH tokens and 3000 as the fee, even though I’m not sure what the fee input does. Please, tell me in the comments if you do!</p><pre>const tokenAAddress = &#39;0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&#39; // USDC<br>const tokenBAddress = &#39;0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2&#39; // WETH<br><br>const txInputs = [<br>  tokenAAddress,<br>  tokenBAddress,<br>  3000<br>]<br><br>const poolAddress = await factoryContract.getPool(...txInputs)<br>console.log(&#39;Pool address:&#39;, poolAddress)</pre><p>This should return <a href="https://etherscan.io/address/0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8">0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8</a> which is the address of a UniswapV3Pool contract for our pair. We will need its ABI as well, so let’s copy it from <a href="https://etherscan.io/address/0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8#code">Etherscan</a> and paste into the file called <em>UniswapV3Pool.json</em> in the <em>contracts</em> folder. Then we will import it and interact with it to get our price data.</p><pre>import uniswapV3PoolAbi from &#39;./contracts/UniswapV3Pool.json&#39;<br><br>...<br><br>const poolContract = new ethers.Contract(poolAddress, uniswapV3PoolAbi, wallet)<br>const slot0 = await poolContract.slot0()</pre><p>Uniswap documentation describes the <em>slot0</em> function in the following way:</p><blockquote>The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas when accessed externally.</blockquote><p>But what’s important to us is that it contains the <em>tick</em> value from which we can calculate the price. Ticks are a way to express a range of prices that the tokens can be between. Ticks are integers so some math needs to be done to calculate the price value. There’s <a href="https://credmark.com/blog/a-technical-analysis-of-uniswap-v3">A Technical Analysis of UniSwap V3</a> article that does a great job of explaining ticks and other features of the UniSwap V3 protocol. Meanwhile I will just give you the algorithm that gets the job done:</p><pre>const { tick } = slot0<br>const tokenBPrice = 1 / ((1.0001 ** tick) * (10 ** -12))<br>    <br>console.log(&#39;Tick:&#39;, tick, &#39;Price:&#39;, tokenBPrice)</pre><p>And we’re done! Our output at the time of writing:</p><pre>0x28C6c06298d514Db089934071355E5743bf21d60: 3561404823107000n<br>Pool address: 0x8ad599c3A0ff1De082011EFDDc58f1908eb6e6D8<br>Tick: 203989 Price: 1384.564588886404</pre><p>I hope you enjoyed the article and by the time you run your app, the price will be higher on its way to the moon :) Join me in the next article where I will attempt to make a swap!</p><p>You can find all the code covered in this story in my <a href="https://github.com/vhalme/dex-bot">DEX-BOT GitHub repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d358412f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I used ChatGPT to develop an application. The world is not the same anymore.]]></title>
            <link>https://medium.com/@vhalme/i-used-chatgpt-to-develop-an-application-the-world-is-not-the-same-anymore-15965031d3c8?source=rss-4f47f535229c------2</link>
            <guid isPermaLink="false">https://medium.com/p/15965031d3c8</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Vladimir Halme]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 17:28:26 GMT</pubDate>
            <atom:updated>2023-01-09T18:06:57.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-lHPo5cQwFlIVti8ozujw.png" /></figure><p>I wanted to learn how to leverage ChatGPT in the software development process so I just started to code a real piece of software I wanted to create but using ChatGPT instead of Google. The software I started to develop is a NodeJS app used for trading on a decentralized exchange (DEX). I want to create a DEX trading bot and the application covered in this article comprises core functionality required by such bot — mainly interaction with a DEX smart contract.</p><p>I am highly proficient with NodeJS but my prior exposure to the subject matter, libraries and tools involved was very limited if not non-existent. I learned much about how the application should work in the process and in retrospect I regard ChatGPT invaluable aid in learning.</p><p>Let’s jump straight into it. I divided the process into two main steps:</p><h3>1. Initialize the app</h3><p>We’ll start by initializing our application. It is a simple task, yet there is some configuration involved that we can’t type in manually from our memory, so let’s ask ChatGPT for help. Even though the following query may look simple, it took me a while to come up with it and I would have managed this step much quicker using my own knowledge and doing a couple of google searches. But this is only because I have no prior experience with ChatGPT and I think that when I learn to express my requirements to it effectively, it will be a powerful tool. Anyway, this is the query that ended up generating instructions meeting my exact requirements.</p><blockquote><strong>Initialize an NPM project with Typescript support and a start script using ts-node.</strong></blockquote><p>The response to this query was a succinct step-by-step instruction with all commands involved and configuration snippets to copy and paste into your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2EJUaYeWIGU6pfKtKnNDw.png" /></figure><p>I was happy with this result but I tried to regenerate the response and the next version was even better! It provided clearer sequence of commands and easy copy-paste access to each of them. It also suggested using the `src` folder and had better instruction for modifying the `package.json` file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sp8CTcmc6LPGdQsRSYbxaw.png" /></figure><h3>2. Contract interaction script</h3><p>Doing this for the first time took me several hours. It was an amazing experience though because during this step I got into an actual workflow using ChatGPT and started to get the feel of its power. Below I will demonstrate a distilled and reworked collection of queries that I would expect myself to use in the future having learned from mistakes of this first experience.</p><p>First let’s try to create the simplest possible script that interacts with a contract on blockchain. I experimented with lots of different ChatGPT queries and each result that was lacking something that I expected guided me to do research (using ChatGPT itself or good old Google). I could then change and refine my query and repeat the process until I was able to ask the correct question. Things that changed in the question were the sentence structure, terminology and libraries I wanted to use.</p><p>My first (unsatisfactory) version of the request was:</p><blockquote>How to interact with a contract on Binance Smart Chain in nodejs using ethers and hardhat libraries?</blockquote><p>After several hours of different query attempts and research I had ended up with:</p><blockquote><strong>Connect to a BSC contract on the BSC mainnet using “ethers” Typescript library and call a contract’s method. Wrap in an exported function.</strong></blockquote><p>This resulted in the response I contended with and was able to use as the basis for the rest of my endeavour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKBbjwi72EV8AEUyZtf6lQ.png" /></figure><p>I imported `callContractMethod` in my `index.ts` file and called it asynchronously with required parameters but that failed due to the following error:</p><p>src/index.ts:3:16 — error TS1378: Top-level ‘await’ expressions are only allowed when the ‘module’ option is set to ‘es2022’, ‘esnext’, ‘system’, ‘node16’, or ‘nodenext’, and the ‘target’ option is set to ‘es2017’ or higher.</p><p>ChatGPT to the rescue and several failed attempts later I had come up with the query:</p><blockquote><strong>How to use top level await with commonjs?</strong></blockquote><p>This finally resulted in the complete solution to my problem and looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYckels35XCrAkEDj00Y-w.png" /></figure><p>Now I could finally execute my code and got confronted with the first error! Yaaay! The cause of the error was the missing contract ABI. At that point I had very little understanding what that even was but ChatGPT stepped in revealing me its mighty glory. Just in few short minutes and 3 or 4 tries I had come up with the following query that returned me the ABI I needed in its entirety. My mind was blown! I love you, ChatGPT!</p><blockquote><strong>Create an ABI for contract 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73 on BSC mainnet, leave out all other functions except ‘allPairsLength’.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVQdouvnrB_0yqUpy9ziRA.png" /></figure><p>Then I sought some help to plug in this ABI to my code.</p><blockquote><strong>Example of contractAbi parameter usage in the Contract constructor of the “ethers” library.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pR9gBL3GRfoAUvDw1pbKJw.png" /></figure><p>The next runtime error was due to the wrong url argument for ethers JsonRpcProvider generated by ChatGPT.</p><p>I had to change</p><pre>// Connect to the BSC mainnet<br>const provider = new ethers.providers.JsonRpcProvider(<br>  &#39;https://api.bscscan.com/api&#39;<br>);</pre><p>To</p><pre>// Connect to the BSC mainnet<br>const provider = new ethers.providers.JsonRpcProvider(<br>  &#39;https://bsc-dataseed.binance.org/&#39;<br>);</pre><p>And then it had actually worked!</p><pre>&gt; dex-bot@1.0.0 start<br>&gt; ts-node src/index.ts</pre><pre>Hello, world!<br>[ BigNumber { _hex: &#39;0x1290d7&#39;, _isBigNumber: true } ]</pre><h3>Conclusion</h3><p>Even though I spent more time creating this application than I would have using Google, the time overhead was mostly due to my inexperience with ChatGPT. I think the end result was also higher quality than it would have been without ChatGPT and I understood the code that I used better. I also thought that when I used ChatGPT my effort was better directed towards my goal, compared to Google where the selection of a solution locks you in to the chosen way of implementation. My mind is officially blown, I don’t see my future without this tool anymore and I look forward to the next coding session!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15965031d3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>