<?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 Olame Galien Muhindo on Medium]]></title>
        <description><![CDATA[Stories by Olame Galien Muhindo on Medium]]></description>
        <link>https://medium.com/@galiendev?source=rss-a429d7a167bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VJvo3KDxqNEhjE8sJvp-Dg.jpeg</url>
            <title>Stories by Olame Galien Muhindo on Medium</title>
            <link>https://medium.com/@galiendev?source=rss-a429d7a167bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:06:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@galiendev/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[Here’s Something I Learned Along the Way: ML Serving Is a Capacity Problem]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@galiendev/heres-something-i-learned-along-the-way-ml-serving-is-a-capacity-problem-464b4f8d41ac?source=rss-a429d7a167bf------2"><img src="https://cdn-images-1.medium.com/max/2600/1*4DTLJ88hwDk78MJ-7zsB2g.png" width="2800"></a></p><p class="medium-feed-snippet">Why CPU-based autoscaling breaks under flash-sale traffic, and what to do instead</p><p class="medium-feed-link"><a href="https://medium.com/@galiendev/heres-something-i-learned-along-the-way-ml-serving-is-a-capacity-problem-464b4f8d41ac?source=rss-a429d7a167bf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@galiendev/heres-something-i-learned-along-the-way-ml-serving-is-a-capacity-problem-464b4f8d41ac?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/464b4f8d41ac</guid>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 02:50:25 GMT</pubDate>
            <atom:updated>2026-10-17T02:50:25.288Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Async Python From the Event Loop Up]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@galiendev/async-python-from-the-event-loop-up-b308bc6722e0?source=rss-a429d7a167bf------2"><img src="https://cdn-images-1.medium.com/max/2600/1*tPD5_wHnfFzWhVDQ-nsC6w.png" width="2760"></a></p><p class="medium-feed-snippet">coroutines, the event loop, cancellation, backpressure, and races, with every example executed and measured.</p><p class="medium-feed-link"><a href="https://medium.com/@galiendev/async-python-from-the-event-loop-up-b308bc6722e0?source=rss-a429d7a167bf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@galiendev/async-python-from-the-event-loop-up-b308bc6722e0?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b308bc6722e0</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[asyncio-best-practices]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 19:25:55 GMT</pubDate>
            <atom:updated>2026-08-31T19:25:55.906Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Graceful Shutdown in Go: A Deep Dive]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@galiendev/graceful-shutdown-in-go-a-deep-dive-7079668da8b2?source=rss-a429d7a167bf------2"><img src="https://cdn-images-1.medium.com/max/678/1*dKyXWQatPVEfYTICfAHWuw.png" width="678"></a></p><p class="medium-feed-snippet">HTTP servers, long-lived connections, and gRPC &#x2014; one mental model, three implementations.</p><p class="medium-feed-link"><a href="https://medium.com/@galiendev/graceful-shutdown-in-go-a-deep-dive-7079668da8b2?source=rss-a429d7a167bf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@galiendev/graceful-shutdown-in-go-a-deep-dive-7079668da8b2?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7079668da8b2</guid>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[graceful-shutdown]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Mon, 24 Aug 2026 12:52:39 GMT</pubDate>
            <atom:updated>2026-08-24T12:52:39.995Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Fine-Tune using Hugging Face Transformers]]></title>
            <link>https://medium.com/@galiendev/a-complete-guide-to-fine-tune-using-hugging-face-transformers-3983d6aeae71?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3983d6aeae71</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[fine-tuning-transformer]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 19:11:53 GMT</pubDate>
            <atom:updated>2025-08-17T01:54:36.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LiPxPMdo8hR29f3JeWI2Q.png" /></figure><p>Natural Language Processing (NLP) has evolved rapidly with the rise of <strong>pre-trained Transformer models</strong> like BERT, RoBERTa, and GPT. Instead of training models from scratch, we can <strong>fine-tune pre-trained models</strong> on specific tasks such as <strong>sentiment analysis</strong>, <strong>text classification</strong>, or <strong>named entity recognition</strong>.</p><p>In this guide, we’ll walk through a <strong>step-by-step process</strong> to fine-tune a pre-trained model using Hugging Face’s transformers library.<br> Our case study: <strong>Sentiment Analysis on the IMDB Movie Reviews Dataset</strong></p><h4>📌 What We’ll Cover</h4><ol><li>Installing dependencies</li><li>Loading and preparing the IMDB dataset</li><li>Preprocessing and tokenization</li><li>Setting up training arguments</li><li>Initializing the model and trainer</li><li>Fine-tuning the model</li><li>Evaluating performance</li><li>Saving and reusing the fine-tuned model</li></ol><p>Let’s dive in.</p><h4>⚙️ Step 1: Install Dependencies</h4><p>First, ensure you have the <strong>datasets</strong> and <strong>transformers</strong> libraries installed:</p><pre>pip install datasets transformers</pre><h4>📂 Step 2: Load and Explore the Dataset</h4><p>We’ll use Hugging Face’s <strong>datasets</strong> library to load the IMDB dataset. This dataset contains <strong>50,000 labeled movie reviews</strong> (positive/negative).</p><pre>from datasets import load_dataset<br># Load the dataset<br>dataset = load_dataset(&quot;imdb&quot;)<br># Print metadata<br>print(dataset)</pre><p><strong>Output:</strong></p><pre>DatasetDict({<br>    train: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 25000<br>    })<br>    test: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 25000<br>    })<br>    unsupervised: Dataset({<br>        features: [&#39;text&#39;, &#39;label&#39;],<br>        num_rows: 50000<br>    })<br>})</pre><p>Each sample contains a <strong>movie review</strong> and a <strong>label</strong> (0 = negative, 1 = positive).</p><p>Example review:</p><pre>print(dataset[&quot;train&quot;][0])</pre><pre>{&#39;text&#39;: &#39;I rented I AM CURIOUS-YELLOW from my video store because<br>of all the controversy that surrounded it when it was first released<br>in 1967. I also heard that at first it was seized by U.S. customs<br>if it ever tried to enter this country, therefore being a fan of films <br>considered &quot;controversial&quot; I really had to see this for myself.&lt;br /&gt;<br>&lt;br /&gt;The plot is centered around a young Swedish drama student named <br>Lena who wants to learn everything she can about life. In particular she <br>wants to focus her attentions to making some sort of documentary on what <br>the average Swede thought about certain political issues such as the Vietnam <br>War and race issues in the United States. In between asking politicians and <br>ordinary denizens of Stockholm about their opinions on politics, she has sex <br>with her drama teacher, classmates, and married men.&lt;br /&gt;&lt;br /&gt;What kills <br>me about I AM CURIOUS-YELLOW is that 40 years ago, this was considered pornographic.<br> Really, the sex and nudity scenes are few and far between, even then it\&#39;s not shot<br>like some cheaply made porno. While my countrymen mind find it shocking, in reality <br>sex and nudity are a major staple in Swedish cinema. Even Ingmar Bergman, arguably their <br>answer to good old boy John Ford, had sex scenes in his films.&lt;br /&gt;&lt;br /&gt;I do commend <br>the filmmakers for the fact that any sex shown in the film is shown for artistic purposes <br>rather than just to shock people and make money to be shown in pornographic theaters in <br>America. I AM CURIOUS-YELLOW is a good film for anyone wanting to study the meat and<br>potatoes (no pun intended) of Swedish cinema. But really,<br>this film doesn\&#39;t have much of a plot.&#39;, <br>&#39;label&#39;: 0}</pre><h3>🧹 Step 3: Preprocess and Tokenize the Data</h3><p>Before training, we must convert text into <strong>numerical tokens</strong> using a pre-trained tokenizer.</p><pre>from transformers import AutoTokenizer<br># Load BERT tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;bert-base-uncased&quot;)<br># Define tokenization function<br>def tokenize_function(examples):<br>    return tokenizer(examples[&quot;text&quot;], padding=&quot;max_length&quot;, truncation=True)<br># Apply tokenization<br>tokenized_datasets = dataset.map(tokenize_function, batched=True)</pre><p>Example tokenized output:</p><pre>print(tokenized_datasets[&quot;train&quot;][0])</pre><p>You’ll see fields like:</p><ul><li>input_ids → tokenized word indices</li><li>attention_mask → identifies real tokens vs. padding</li><li>token_type_ids → (for sentence pairs)</li></ul><h4>⚡ Step 4: Define Training Arguments</h4><p>We configure <strong>hyperparameters</strong> and <strong>training settings</strong> using TrainingArguments.</p><pre>from transformers import TrainingArguments<br>training_args = TrainingArguments(<br>    output_dir=&quot;results&quot;,   # save models here<br>    eval_strategy=&quot;epoch&quot;,  # evaluate after each epoch<br>    learning_rate=2e-5,      # learning rate<br>    per_device_train_batch_size=4,  # reduce batch size if limited GPU<br>    per_device_eval_batch_size=4, # Batch size for evaluation<br>    num_train_epochs=1,     # for demo, set higher in practice<br>    weight_decay=0.01,<br>)</pre><h3>🏗️ Step 5: Initialize the Model &amp; Trainer</h3><p>We’ll use <strong>BERT (bert-base-uncased)</strong> for sequence classification with 2 labels (positive/negative).</p><pre>from transformers import AutoModelForSequenceClassification, Trainer<br># Load pre-trained model for classification<br>model = AutoModelForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;, num_labels=2)<br><br># Initialize Trainer<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_datasets[&quot;train&quot;],<br>    eval_dataset=tokenized_datasets[&quot;test&quot;]<br>)</pre><h3>🏋️ Step 6: Fine-Tune the Model</h3><p>Now, let’s fine-tune the model on IMDB reviews.</p><pre>print(&quot;---------- Training started----------&quot;)<br>trainer.train()<br>print(&quot;----------Training completed----------&quot;)</pre><pre>Some weights of BertForSequenceClassification were not initialized from the model checkpoint at bert-base-uncased and are newly initialized: [&#39;classifier.bias&#39;, &#39;classifier.weight&#39;]<br>You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.<br> ---------- Training started ----------<br>  0%|                                                                    | 0/6250 [00:00&lt;?, ?it/s]/Users/galien/Documents/ai/mcp-server/venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:684: UserWarning: &#39;pin_memory&#39; argument is set as true but not supported on MPS now, then device pinned memory won&#39;t be used.<br>  warnings.warn(warn_msg)<br>  6%|███▍                                                      | 368/6250 [03:20&lt;56:32,  1.73it/s]                                                                 {&#39;loss&#39;: 0.453, &#39;grad_norm&#39;: 0.4327799081802368, &#39;learning_rate&#39;: 1.84032e-05, &#39;epoch&#39;: 0.08}                                                                      <br>{&#39;loss&#39;: 0.423, &#39;grad_norm&#39;: 52.526954650878906, &#39;learning_rate&#39;: 1.6803200000000002e-05, &#39;epoch&#39;: 0.16}                                                           <br>{&#39;loss&#39;: 0.3922, &#39;grad_norm&#39;: 10.000938415527344, &#39;learning_rate&#39;: 1.52032e-05, &#39;epoch&#39;: 0.24}                                                                     <br>{&#39;loss&#39;: 0.3486, &#39;grad_norm&#39;: 14.510967254638672, &#39;learning_rate&#39;: 1.36032e-05, &#39;epoch&#39;: 0.32}                                                                     <br>{&#39;loss&#39;: 0.369, &#39;grad_norm&#39;: 198.06076049804688, &#39;learning_rate&#39;: 1.2003200000000002e-05, &#39;epoch&#39;: 0.4}                                                            <br>{&#39;loss&#39;: 0.3768, &#39;grad_norm&#39;: 117.08883666992188, &#39;learning_rate&#39;: 1.04032e-05, &#39;epoch&#39;: 0.48}                                                                     <br>{&#39;loss&#39;: 0.342, &#39;grad_norm&#39;: 0.08970938622951508, &#39;learning_rate&#39;: 8.8032e-06, &#39;epoch&#39;: 0.56}                                                                      <br>{&#39;loss&#39;: 0.3398, &#39;grad_norm&#39;: 20.2169132232666, &#39;learning_rate&#39;: 7.2032e-06, &#39;epoch&#39;: 0.64}                                                                        <br>{&#39;loss&#39;: 0.3242, &#39;grad_norm&#39;: 70.76058959960938, &#39;learning_rate&#39;: 5.603200000000001e-06, &#39;epoch&#39;: 0.72}                                                            <br>{&#39;loss&#39;: 0.3138, &#39;grad_norm&#39;: 66.68832397460938, &#39;learning_rate&#39;: 4.0032e-06, &#39;epoch&#39;: 0.8}                                                                        <br>{&#39;loss&#39;: 0.2953, &#39;grad_norm&#39;: 16.9731388092041, &#39;learning_rate&#39;: 2.4032e-06, &#39;epoch&#39;: 0.88}                                                                        <br>{&#39;loss&#39;: 0.2799, &#39;grad_norm&#39;: 14.353861808776855, &#39;learning_rate&#39;: 8.032000000000001e-07, &#39;epoch&#39;: 0.96}                                                           <br>100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6250/6250 [58:43&lt;00:00,  1.98it/s]/Users/galien/Documents/ai/mcp-server/venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:684: UserWarning: &#39;pin_memory&#39; argument is set as true but not supported on MPS now, then device pinned memory won&#39;t be used.<br>  warnings.warn(warn_msg)<br>{&#39;eval_loss&#39;: 0.26994386315345764, &#39;eval_runtime&#39;: 738.8534, &#39;eval_samples_per_second&#39;: 33.836, &#39;eval_steps_per_second&#39;: 8.459, &#39;epoch&#39;: 1.0}                      <br>{&#39;train_runtime&#39;: 4263.8654, &#39;train_samples_per_second&#39;: 5.863, &#39;train_steps_per_second&#39;: 1.466, &#39;train_loss&#39;: 0.3548667651367188, &#39;epoch&#39;: 1.0}                   <br>100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6250/6250 [1:11:03&lt;00:00,  1.47it/s]<br> ---------- Training completed ----------</pre><h3>📊 Step 7: Evaluate the Model</h3><p>We can now test the model’s performance.</p><pre>results = trainer.evaluate()<br>print(results)</pre><p>Expected output includes:</p><ul><li>eval_loss</li><li>eval_runtime</li><li>eval_samples_per_second</li></ul><p>The lower the loss, the better the model is performing.</p><p>Output:</p><pre>100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6250/6250 [12:46&lt;00:00,  8.15it/s]<br>{&#39;eval_loss&#39;: 0.6899533867835999, &#39;eval_model_preparation_time&#39;: 0.0011, &#39;eval_runtime&#39;: 745.346, &#39;eval_samples_per_second&#39;: 33.541, &#39;eval_steps_per_second&#39;: 8.385}<br></pre><h3>💾 Step 8: Save the Fine-Tuned Model</h3><p>Finally, save both the <strong>model</strong> and <strong>tokenizer</strong> for future inference.</p><pre>model.save_pretrained(&quot;./fine-tuned-model&quot;)<br>tokenizer.save_pretrained(&quot;./fine-tuned-model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*NYDEha5e_OcC0kEdN-kJ0w.png" /></figure><p>Now, you can load this model later with:</p><pre>from transformers import pipeline<br>sentiment_model = pipeline(&quot;sentiment-analysis&quot;, model=&quot;./fine-tuned-model&quot;, tokenizer=&quot;./fine-tuned-model&quot;)<br>print(sentiment_model(&quot;The movie was absolutely fantastic!&quot;))</pre><h3>Final Thoughts</h3><p>In this tutorial, we:</p><ul><li>Loaded the IMDB dataset using Hugging Face Datasets</li><li>Preprocessed and tokenized text with BERT’s tokenizer</li><li>Fine-tuned a pre-trained Transformer for sentiment analysis</li><li>Evaluated and saved the model</li></ul><p>This workflow can be adapted for <strong>other datasets and tasks</strong> like spam detection, emotion classification, or topic modeling.</p><p><strong>Pro Tip:</strong> For better results, try:</p><ul><li>Training for <strong>3–5 epochs</strong></li><li>Using a larger batch size (if GPU allows)</li><li>Experimenting with models like <strong>RoBERTa, DistilBERT, or DeBERTa</strong></li></ul><p>You now have a <strong>production-ready fine-tuned model</strong> built with Hugging Face!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3983d6aeae71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Building a Basic (Naive) RAG — Part 1 of my RAG Series]]></title>
            <link>https://medium.com/@galiendev/a-complete-guide-to-building-a-basic-naive-rag-part-1-of-my-rag-series-7def6f0b3b93?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7def6f0b3b93</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:00:27 GMT</pubDate>
            <atom:updated>2025-08-12T12:00:27.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Complete Guide to Building a Basic (Naive) RAG — Part 1 of my RAG Series</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZ5JO88OEM44MJmkcCDtIA.png" /></figure><p>RAG (Retrieval‑Augmented Generation) lets an LLM answer questions using <strong>your</strong> documents. In this first post of the series we’ll build a <strong>basic / naive RAG</strong>: index some files, retrieve the most relevant chunks for a query, then <strong>augment</strong> the LLM prompt with those chunks to get a grounded answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf_JLIVeixS-rB2uEW-zQw.png" /><figcaption>Free code camp image</figcaption></figure><p>We’ll use <strong>Python</strong>, <strong>ChromaDB</strong> for the vector store, local sentence‑transformer embeddings (so you can run it without paying for embedding calls), and <strong>OpenAI</strong> for generation. I’ll keep code snippets compact and runnable, with room for you to expand.</p><h3>What you’ll build</h3><ul><li>A small script that:</li></ul><ol><li>loads your docs (TXT ),</li><li>splits them into chunks,</li><li>embeds + stores them in Chroma,</li><li>retrieves top‑k chunks for a question,</li><li>asks an LLM to answer <strong>using only those chunks</strong>.</li></ol><h3>Prerequisites</h3><ul><li>Python 3.9+</li><li>A code editor (VS Code recommended)</li><li>An OpenAI API key in a .env file as OPENAI_API_KEY=...</li><li>A few documents (plain text or a PDF) to query</li></ul><p><em>Tip: Start with a tidy </em><em>data/ folder. You can use a mix of </em><em>.txt files and a PDF.</em></p><h3>0) Project scaffold</h3><pre>mkdir rag-basic &amp;&amp; cd rag-basic<br>python -m venv .venv<br># macOS/Linux<br>source .venv/bin/activate<br># Windows<br># .venv\Scripts\activate</pre><p>Create folders and starter files:</p><pre>rag-basic/<br>├─ .env<br>├─ news_articles/<br>│  ├─ article1.txt<br>│  └─ article2.txt<br>└─ app.py</pre><p>.env:</p><pre>OPENAI_API_KEY=sk-...</pre><h3>1) Install dependencies</h3><p>We’ll keep it minimal for a basic RAG:</p><pre>python3 -m venv venv<br>pip install python-dotenv openai chromadb</pre><p>(Optionally for plots later in the series: pip install umap-learn matplotlib numpy.)</p><h3>2) The minimal RAG pipeline (index → retrieve → generate)</h3><h4>2.1 Imports, env, and clients</h4><p>Open app.py and paste the snippets in each step.</p><pre># app.py<br>from dotenv import load_dotenv<br>from openai import OpenAI<br>from chromadb.utils import embedding_functions<br>import chromadb<br>import os<br><br>load_dotenv()<br><br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>assert OPENAI_API_KEY, &quot;Set OPENAI_API_KEY in your .env&quot;<br><br># Embedding function (OpenAI)<br>openai_ef = embedding_functions.OpenAIEmbeddingFunction(<br>    api_key=OPENAI_API_KEY,<br>    model_name=&quot;text-embedding-3-small&quot;,<br>)<br><br># Chroma client (persistent on disk)<br>chroma_client = chromadb.PersistentClient(path=&quot;chroma_db&quot;)<br><br># One collection per project/task<br>COLLECTION_NAME = &quot;document_qa_collection&quot;<br>collection = chroma_client.get_or_create_collection(<br>    name=COLLECTION_NAME,<br>    embedding_function=openai_ef<br>)<br><br># OpenAI chat client<br>oa = OpenAI(api_key=OPENAI_API_KEY)</pre><h4>2.2 Load your documents</h4><p>We’ll support <strong>TXT,</strong> Add this to app.py.</p><pre># app.py<br>def load_documents(directory: str):<br>    print(f&quot;Loading documents from {directory} ...&quot;)<br>    docs = []<br>    for filename in os.listdir(directory):<br>        if filename.endswith(&quot;.txt&quot;):<br>            with open(os.path.join(directory, filename), &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>                docs.append({&quot;id&quot;: filename, &quot;text&quot;: f.read()})<br>    print(f&quot;Loaded {len(docs)} documents&quot;)<br>    return docs<br><br>documents = load_documents(&quot;./news_articles&quot;)</pre><h3>2.3 Split text into overlapping chunks</h3><p>Chunking preserves context while staying under token limits.</p><pre>def split_text(text: str, chunk_size=1000, chunk_overlap=200):<br>    chunks, start = [], 0<br>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunks.append(text[start:end])<br>        # step forward but overlap a little to keep context<br>        start = end - chunk_overlap<br>    return chunks<br><br># Expand docs into chunked docs with unique IDs<br>chunked_docs = []<br>for doc in documents:<br>    chunks = split_text(doc[&quot;text&quot;])<br>    for i, chunk in enumerate(chunks, start=1):<br>        chunked_docs.append({<br>            &quot;id&quot;: f&quot;{doc[&#39;id&#39;]}_chunk{i}&quot;,<br>            &quot;text&quot;: chunk,<br>            &quot;source&quot;: doc[&quot;id&quot;],<br>            &quot;chunk_index&quot;: i<br>        })<br><br>print(f&quot;Split into {len(chunked_docs)} chunks&quot;)</pre><h3>2.4 Create embeddings and index into Chroma</h3><p>We’ll embed each chunk and upsert into the collection.<br> (Chroma can also embed for you via the embedding_function, but doing it explicitly makes the flow clear.)</p><pre>def get_openai_embedding(text: str):<br>    res = oa.embeddings.create(model=&quot;text-embedding-3-small&quot;, input=text)<br>    return res.data[0].embedding<br><br># Upsert all chunks with precomputed embeddings<br>for d in chunked_docs:<br>    emb = get_openai_embedding(d[&quot;text&quot;])<br>    collection.upsert(<br>        ids=[d[&quot;id&quot;]],<br>        documents=[d[&quot;text&quot;]],<br>        metadatas=[{&quot;source&quot;: d[&quot;source&quot;], &quot;chunk_index&quot;: d[&quot;chunk_index&quot;]}],<br>        embeddings=[emb],<br>    )<br><br>print(&quot;Indexing complete ✅&quot;)</pre><h3>2.5 Retrieve the most relevant chunks</h3><pre>def query_documents(question: str, n_results=4):<br>    print(&quot;Retrieving relevant chunks ...&quot;)<br>    res = collection.query(<br>        query_texts=[question],<br>        n_results=n_results,<br>        include=[&quot;documents&quot;, &quot;metadatas&quot;, &quot;distances&quot;, &quot;ids&quot;]<br>    )<br>    # Flatten results from Chroma’s list-of-lists shape<br>    docs = res[&quot;documents&quot;][0]<br>    metas = res[&quot;metadatas&quot;][0]<br>    ids = res[&quot;ids&quot;][0]<br>    dists = res.get(&quot;distances&quot;, [[None]*len(docs)])[0]<br><br>    for i, (cid, meta, dist) in enumerate(zip(ids, metas, dists), start=1):<br>        print(f&quot;{i}. {meta[&#39;source&#39;]} (chunk {meta[&#39;chunk_index&#39;]})  distance={dist:.4f}&quot;)<br><br>    return docs</pre><p><strong>Why distances?</strong> It’s useful to see how “close” each chunk is to the query in vector space (lower is closer).</p><h4>2.6 Generate a final answer with the retrieved context</h4><p>This is the “G” in RAG: we pass the retrieved snippets to the chat model.</p><pre>def generate_response(question: str, retrieved_chunks: list[str]):<br>    context = &quot;\n\n&quot;.join(retrieved_chunks)<br>    system = (<br>        &quot;You are an assistant for question-answering tasks. &quot;<br>        &quot;Use the provided context to answer the user succinctly. &quot;<br>        &quot;If the answer is not in the context, say you don&#39;t know.&quot;<br>    )<br>    user = f&quot;Context:\n{context}\n\nQuestion:\n{question}&quot;<br><br>    completion = oa.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,  # swap for your preferred model<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user},<br>        ],<br>        temperature=0.2,<br>    )<br>    return completion.choices[0].message.content.strip()</pre><h3>2.7 Wire it up (ask your first question)</h3><pre>if __name__ == &quot;__main__&quot;:<br>    question = &quot;Tell me about AI replacing TV writers in the strike.&quot;<br>    top_chunks = query_documents(question, n_results=4)<br>    answer = generate_response(question, top_chunks)<br>    print(&quot;\n--- Answer ---&quot;)<br>    print(answer)</pre><h4>Run it</h4><pre>python app.py</pre><p>You should see the top‑matching chunks printed (with distance scores), followed by a short, sourced answer that references your documents.</p><h3>3) What “naive RAG” is (and why it’s enough for now)</h3><p>Naive (basic) RAG has three phases:</p><ol><li><strong>Indexing</strong> — clean, chunk, embed, store</li><li><strong>Retrieval</strong> — embed the question and perform a similarity search</li><li><strong>Generation</strong> — stuff retrieved text + question into a prompt for the LLM</li></ol><p>It’s a great starting point: the pipeline is clear, fast to build, and works well for small/clean corpora.</p><h3>4) Try these quick experiments</h3><ul><li>Change chunk_size (e.g., 800 vs 1200) and chunk_overlap (50–250). How does answer quality change?</li><li>Ask a question you <em>know</em> isn’t covered by your docs — does the model say “I don’t know”?</li><li>Raise n_results to 6–8 and watch for noise versus coverage.</li></ul><h3>Full minimal script (for copy/paste)</h3><p>You already pasted the pieces above; here’s the same flow compacted so you can run it end‑to‑end and tweak.</p><pre>from dotenv import load_dotenv<br>from openai import OpenAI<br>from chromadb.utils import embedding_functions<br>import chromadb<br>import os<br><br>load_dotenv()<br><br>#load env variables<br>openai_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br><br>#create embedding function that vectorizes data and son get store in chroma db<br>openai_ef = embedding_functions.OpenAIEmbeddingFunction(api_key=openai_key,model_name=&quot;text-embedding-3-small&quot;)<br><br>#Initialize chroma client with persistent storage<br>chromadb_client = chromadb.PersistentClient(path=&quot;chroma_db&quot;)<br><br>#create collection that will automatically store the vectorized data<br>collection_name = &quot;document_qa_colleciton&quot;<br>collection = chromadb_client.get_or_create_collection(name=collection_name, embedding_function=openai_ef)<br><br>#create OpenAI client<br>openai_client = OpenAI(api_key=openai_key)<br><br><br>response = openai_client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant that can answer questions about the documents in the collection.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;What is the main idea of the document?&quot;}<br>    ]<br>)<br><br># load the documents from a directory<br>def load_documents(directory):<br>    print(f&quot;Loading documents from {directory}&quot;)<br>    documents = []<br>    for filename in os.listdir(directory):<br>        if filename.endswith(&quot;.txt&quot;):<br>            with open(os.path.join(directory, filename), &quot;r&quot;) as f:<br>                documents.append({&quot;id&quot;: filename, &quot;text&quot;: f.read()})<br>    return documents<br><br># #Split the text into chunks<br>def split_text(text, chunk_size=1000, chunk_overlap=20):<br>    chunks = []<br>    start = 0<br>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunks.append(text[start:end])<br>        start = end - chunk_overlap<br>    return chunks<br><br># #load the documents<br>documents = load_documents(&quot;./news_articles&quot;)<br>print(&quot;Number of documents loaded:&quot;, len(documents))<br><br># # Split documents into chunks<br>chunked_documents = []<br>for doc in documents:<br>    chunks = split_text(doc[&quot;text&quot;])<br>    print(&quot;==== Splitting docs into chunks ====&quot;, &quot;\n&quot;)<br>    for i, chunk in enumerate(chunks):<br>        chunked_documents.append({&quot;id&quot;: f&quot;{doc[&#39;id&#39;]}_chunk{i+1}&quot;, &quot;text&quot;: chunk})<br><br>print(f&quot;Split documents into {len(chunked_documents)} chunks&quot;, &quot;\n&quot;)<br><br># #create a function to generate embedding for each chunk using openai<br>def get_openai_embedding(text):<br>    response = openai_client.embeddings.create(input=text, model=&quot;text-embedding-3-small&quot;)<br>    embedding = response.data[0].embedding<br>    print(&quot;==== Generating embeddings... ====&quot;)<br>    return embedding<br><br><br># # Generate embeddings for the document chunks<br>for doc in chunked_documents:<br>    print(&quot;==== Generating embeddings... ====&quot;)<br>    # adding the embedding to the chunked_documents list for each chunk<br>    doc[&quot;embedding&quot;] = get_openai_embedding(doc[&quot;text&quot;])<br><br><br># # Add  the document with embedding to the collection<br>for doc in chunked_documents:<br>    collection.upsert(<br>        documents=[doc[&quot;text&quot;]],<br>        ids=[doc[&quot;id&quot;]],<br>        embeddings=[doc[&quot;embedding&quot;]]<br>    )<br><br>#Query Function to get the most relevant chunks<br>def query_documents(questions,n_results=3):<br>    print(&quot;==== Querying documents... ====&quot;)<br>    # query the collection for the most relevant chunks<br>    results =  collection.query(query_texts= questions, n_results=n_results)<br><br>    # Extract the relevant chunks<br>    relevant_chunks = [doc for sublist in results[&quot;documents&quot;] for doc in sublist]<br>    print(&quot;==== Returning relevant chunks ====&quot;)<br><br>    #return the relevant chunks<br>    return relevant_chunks<br><br># Function to generate a response from OpenAI<br>def generate_response(question, relevant_chunks):<br>    context = &quot;\n\n&quot;.join(relevant_chunks)<br>    prompt = (<br>        &quot;You are an assistant for question-answering tasks. Use the following pieces of &quot;<br>        &quot;retrieved context to answer the question. If you don&#39;t know the answer, say that you &quot;<br>        &quot;don&#39;t know. Use three sentences maximum and keep the answer concise.&quot;<br>        &quot;\n\nContext:\n&quot; + context + &quot;\n\nQuestion:\n&quot; + question<br>    )<br><br>    response = openai_client.chat.completions.create(<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        messages=[<br>            {<br>                &quot;role&quot;: &quot;system&quot;,<br>                &quot;content&quot;: prompt, <br>            },<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: question,<br>            },<br>        ],<br>    )<br><br>    answer = response.choices[0].message<br>    return answer<br><br><br>question = &quot;Tell me about AI replacing TV writters strike&quot;<br>relevant_chunks = query_documents(question)<br>response = generate_response(question, relevant_chunks)<br>print(response)</pre><h3>7) Where this “Basic RAG” falls short (and what’s next)</h3><p>Naive RAG is intentionally simple. As your corpus grows, you’ll notice:</p><ul><li>Sometimes the retrieved chunks are <strong>close</strong> but not quite what you need.</li><li>The LLM might ignore key context (or hallucinate).</li><li>Large corpora need better indexing, <strong>reranking</strong>, and smarter <strong>query expansion</strong>.</li></ul><p>In the next post of this series, we’ll harden retrieval with practical upgrades:</p><ul><li><strong>Query expansion</strong> (generated answers &amp; multi‑query)</li><li><strong>Reranking</strong> (to filter noise)</li><li><strong>Prompt packing</strong> patterns that keep answers grounded</li></ul><p>[VISUAL: teaser diagram showing “Naive RAG → Advanced RAG path”]</p><h3>Cheatsheet summary</h3><ul><li><strong>Index:</strong> chunk → embed → upsert</li><li><strong>Retrieve:</strong> embed query → similarity search → top‑k chunks</li><li><strong>Generate:</strong> pack context + question → LLM → concise grounded answer</li></ul><p>That’s it — you’ve got a working Basic RAG. Tweak chunk sizes, add your own docs, and see how far it gets you. Then let’s level it up in Part 2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7def6f0b3b93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Upgradable Smart Contracts on StarkNet]]></title>
            <link>https://medium.com/coinmonks/building-upgradable-smart-contracts-on-starknet-033648e2ee96?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/033648e2ee96</guid>
            <category><![CDATA[cairo-lang]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[upgradeable-contract]]></category>
            <category><![CDATA[openzeppelin]]></category>
            <category><![CDATA[starknet]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 22:42:23 GMT</pubDate>
            <atom:updated>2025-01-15T11:36:51.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plDmdaCNHKuHw0b-tFWoDQ.png" /></figure><h3>Building Upgradable Smart Contracts on StarkNet</h3><p>Smart contracts on StarkNet provide a solid foundation for building decentralized applications. Using OpenZeppelin’s libraries and the StarkNet Foundry (snforge), you can create upgradable contracts that allow updates without losing existing data or functionality. This guide will take you through the steps to set up your environment, create an upgradable contract, and handle deployment and upgrades effectively.</p><h3>Prerequisites</h3><p>Before starting, ensure you have:</p><ul><li>A basic understanding of Cairo programming language.</li><li>The latest version of Scarb installed. If not, <a href="https://github.com/software-mansion/asdf-scarb">install</a> it here.</li></ul><h3>Setting Up the Environment</h3><h3>Step 1: Initialize the Project</h3><p>Run the following commands to initialize a project:</p><pre>npm init -y<br>snforge new</pre><h3>Step 2: Configure Scarb.toml</h3><p>Open your Scarb.toml file and add the following dependencies and configurations:</p><pre>[dependencies]<br>openzeppelin = { git = &quot;https://github.com/OpenZeppelin/cairo-contracts.git&quot;, tag = &quot;v0.20.0&quot; }<br>[dependencies]<br>openzeppelin = { git = &quot;https://github.com/OpenZeppelin/cairo-contracts.git&quot;, tag = &quot;v0.20.0&quot; }<br><br>[[target.starknet-contract]]<br>allowed-libfuncs-list.name = &quot;experimental&quot;<br>sierra = true<br>casm = true<br><br>[tool.fmt]<br>sort-module-level-items = true<br>max-line-length = 120</pre><h3>Step 3: Install Node.js Dependencies</h3><p>Install the required Node.js libraries:</p><pre>npm install dotenv starknet</pre><h3>Step 4: Add .env File</h3><p>Create a .env file in your project root and populate it with the following variables:</p><pre>DEPLOYER_PRIVATE_KEY=<br>DEPLOYER_ADDRESS=<br>RPC_ENDPOINT=https://starknet-sepolia.public.blastapi.io/<br></pre><h3>Step 5: Creating the Contract</h3><p>Navigate to the src folder and open the lib.cairo file. Add the following contract code:</p><pre>#[starknet::interface]<br>trait ITry&lt;TContractState&gt; {<br>    fn get_value(self: @TContractState) -&gt; u128;<br>    fn increase_value(ref self: TContractState) -&gt; u128;<br>}<br><br>#[starknet::contract]<br>mod gammer {<br>    use openzeppelin::access::ownable::OwnableComponent;<br>    use openzeppelin::upgrades::interface::IUpgradeable;<br>    use openzeppelin::upgrades::UpgradeableComponent;<br>    use starknet::{ClassHash, ContractAddress};<br>    component!(path: UpgradeableComponent, storage: upgradeable, event: UpgradeableEvent);<br>    component!(path: OwnableComponent, storage: ownable, event: OwnableEvent);<br>    #[abi(embed_v0)]<br>    impl OwnableMixinImpl = OwnableComponent::OwnableMixinImpl&lt;ContractState&gt;;<br>    impl OwnableInternalImpl = OwnableComponent::InternalImpl&lt;ContractState&gt;;<br>    impl UpgradeableInternalImpl = UpgradeableComponent::InternalImpl&lt;ContractState&gt;;<br><br>    #[storage]<br>    struct Storage {<br>        #[substorage(v0)]<br>        ownable: OwnableComponent::Storage,<br>        #[substorage(v0)]<br>        upgradeable: UpgradeableComponent::Storage,<br>        value: u128,<br>        name: felt252<br>    }<br><br>    #[event]<br>    #[derive(Drop, starknet::Event)]<br>    enum Event {<br>        #[flat]<br>        OwnableEvent: OwnableComponent::Event,<br>        #[flat]<br>        UpgradeableEvent: UpgradeableComponent::Event,<br>    }<br><br>    #[constructor]<br>    fn constructor(ref self: ContractState, owner: ContractAddress, initial_value: u128) {<br>        self.ownable.initializer(owner);<br>        self.value.write(initial_value);<br>    }<br><br>    #[abi(embed_v0)]<br>    impl TryImpl of super::ITry&lt;ContractState&gt; {<br>        fn get_value(self: @ContractState) -&gt; u128 {<br>            self.value.read()<br>        }<br>        fn increase_value(ref self: ContractState) -&gt; u128 {<br>            self.value.write(self.value.read() + 1);<br>            self.value.read()<br>        }<br>    }<br><br>    #[abi(embed_v0)]<br>    impl UpgradeableImpl of IUpgradeable&lt;ContractState&gt; {<br>        fn upgrade(ref self: ContractState, new_class_hash: ClassHash) {<br>            self.ownable.assert_only_owner();<br>            self.upgradeable.upgrade(new_class_hash);<br>        }<br>    }<br>}</pre><h3>Short Explanation of the gammer Contract</h3><p>This Cairo smart contract demonstrates how to build an <strong>upgradable smart contract</strong> on StarkNet using OpenZeppelin’s libraries. The primary features include:</p><ol><li><strong>Ownership and Upgradeability</strong>:</li></ol><ul><li>The contract uses the OwnableComponent to enforce that only the owner can perform specific actions, such as upgrades.</li><li>The UpgradeableComponent provides functionality to update the contract&#39;s implementation (ClassHash) without losing the existing state.</li></ul><p><strong>2. State Management</strong>:</p><ul><li>Stores a value (a u128 integer) that can be retrieved or incremented using exposed functions.</li><li>Implements an upgradeable structure that ensures the contract’s state variables remain consistent across upgrades.</li></ul><p><strong>3. Key Functions</strong>:</p><ul><li><strong>get_value</strong>: Reads the current value stored in the contract.</li><li><strong>increase_value</strong>: Increments the stored value by 1.</li><li><strong>upgrade</strong>: Allows the contract owner to update the implementation using a new ClassHash.</li></ul><p><strong>4. Upgradability</strong>:</p><ul><li>The upgrade function ensures future-proofing by allowing the contract&#39;s functionality to evolve while retaining its state.</li><li>This is achieved using the OpenZeppelin IUpgradeable interface and UpgradeableComponent.</li></ul><p><strong>4. Events</strong>:</p><ul><li>Tracks important actions, such as upgrades and ownership changes, via emitted events.</li></ul><p>This contract is a foundational example of how to use OpenZeppelin’s tools to manage <strong>ownership</strong> and <strong>upgrades</strong>, ensuring secure and scalable smart contract deployments on StarkNet.</p><h3>Declaring and Deploying the Contract</h3><h3>Step 6: Create Scripts Folder</h3><p>Create a scripts folder and add a deploymentsOrDeclare.ts file. Paste the following code:</p><pre>import { Account, CallData, Contract, RpcProvider, stark } from &quot;starknet&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import fs from &quot;fs&quot;;<br>import path from &quot;path&quot;;<br>import { getCompiledCode } from &quot;./utils&quot;;<br>dotenv.config({ path: __dirname + &quot;/../.env&quot; });<br><br>async function main() {<br>  const provider = new RpcProvider({<br>    nodeUrl: process.env.RPC_ENDPOINT,<br>  });<br><br>  // initialize existing predeployed account 0<br>  console.log(&quot;ACCOUNT_ADDRESS=&quot;, process.env.DEPLOYER_ADDRESS);<br>  console.log(&quot;ACCOUNT_PRIVATE_KEY=&quot;, process.env.DEPLOYER_PRIVATE_KEY);<br>  const privateKey0 = process.env.DEPLOYER_PRIVATE_KEY ?? &quot;&quot;;<br>  const accountAddress0: string = process.env.DEPLOYER_ADDRESS ?? &quot;&quot;;<br>  const account0 = new Account(provider, accountAddress0, privateKey0);<br>  console.log(&quot;Account connected.\n&quot;);<br>  <br>  let name = &quot;new_gammer&quot;;<br><br>  // Define the path to the .env file<br>  const envFilePath = path.resolve(__dirname, &quot;../.env&quot;);<br><br>  // Declare <br>  let sierraCode, casmCode;<br><br>  try {<br>    ({ sierraCode, casmCode } = await getCompiledCode(<br>      &quot;gammer_gammer&quot;<br>    ));<br>  } catch (error: any) {<br>    console.log(&quot;Failed to read contract files&quot;);<br>    process.exit(1);<br>  }<br><br>  const declareResponse = await account0.declare({<br>    contract: sierraCode,<br>    casm: casmCode,<br>  });<br><br>  console.log(&quot;Contract classHash: &quot;, declareResponse.class_hash);<br><br>  fs.appendFileSync(<br>    envFilePath,<br>    `\n${name.toUpperCase()}_CLASS_HASH=${declareResponse.class_hash}`<br>  );<br><br>  // =============================================================================<br>  // Deployment<br>  const myCallData = new CallData(sierraCode.abi);<br>  const constructor = myCallData.compile(&quot;constructor&quot;, {<br>    owner: &quot;0x0118093daad51ef5c39b07201ee09e48edeffaa12e3fbb33d6d0c65eb00dfdfa&quot;,<br>    intial_value: 10,<br>  });<br>  <br>  const { transaction_hash, contract_address } = await account0.deploy({<br>    classHash: process.env.GAMMER_CLASS_HASH as string,<br>    constructorCalldata: constructor,<br>    salt: stark.randomAddress(),<br>  });<br><br>  const contractAddress: any = contract_address[0];<br>  await provider.waitForTransaction(transaction_hash);<br><br>  // Connect the new contract instance :<br>  const try_contract = new Contract(sierraCode.abi, contractAddress, provider);<br><br>  console.log(`✅ Contract has been connected at: ${try_contract.address}`);<br><br>  fs.appendFileSync(<br>    envFilePath,<br>    `\n${name.toUpperCase()}_ADDRESS=${contractAddress}`<br>  );<br>}<br>main()<br>  .then(() =&gt; process.exit(0))<br>  .catch((error) =&gt; {<br>    console.error(error);<br>    process.exit(1);<br>  });</pre><h3>Step 7: Add Scripts to package.json</h3><p>Update your package.json file:</p><pre>&quot;scripts&quot;: {<br>    &quot;deploy-gammer&quot;: &quot;ts-node scripts/deploymentsOrDeclare.ts&quot;,<br>    &quot;upgrade&quot;: &quot;ts-node scripts/upgradeContracts.ts&quot;<br>}</pre><h3>Step 8: Declare and Deploy</h3><p>Run the following commands to build and declare:</p><pre>scarb build &amp;<br>npm run deploy-gammer</pre><p>A new environment variable is automatically appended to your .env file: GAMMER_CLASS_HASH &amp; GAMMER_ADDRESS</p><h3>Step 9: Upgrading the Contract</h3><p>To make the contract upgradable, add a new function to decrease the value. Update the ITry and TryImpl implementations.</p><h3>Updated Contract:</h3><pre> #[starknet::interface]<br>trait ITry&lt;TContractState&gt; {<br>    fn get_value(self: @TContractState) -&gt; u128;<br>    fn increase_value(ref self: TContractState) -&gt; u128;<br>    //new function<br>    fn decrease_value(ref self: TContractState) -&gt; u128;<br>}<br><br>#[starknet::contract]<br>mod gammer {<br>    use openzeppelin::access::ownable::OwnableComponent;<br>    use openzeppelin::upgrades::interface::IUpgradeable;<br>    use openzeppelin::upgrades::UpgradeableComponent;<br>    use starknet::{ClassHash, ContractAddress};<br><br>    component!(path: UpgradeableComponent, storage: upgradeable, event: UpgradeableEvent);<br>    component!(path: OwnableComponent, storage: ownable, event: OwnableEvent);<br><br><br>    #[abi(embed_v0)]<br>    impl OwnableMixinImpl = OwnableComponent::OwnableMixinImpl&lt;ContractState&gt;;<br>    impl OwnableInternalImpl = OwnableComponent::InternalImpl&lt;ContractState&gt;;<br>    // Upgradeable<br>    impl UpgradeableInternalImpl = UpgradeableComponent::InternalImpl&lt;ContractState&gt;;<br><br>    #[storage]<br>    struct Storage {<br>        #[substorage(v0)]<br>        ownable: OwnableComponent::Storage,<br>        #[substorage(v0)]<br>        upgradeable: UpgradeableComponent::Storage,<br>        value: u128,<br>        name: felt252<br>    }<br><br>    #[event]<br>    #[derive(Drop, starknet::Event)]<br>    enum Event {<br>        #[flat]<br>        OwnableEvent: OwnableComponent::Event,<br>        #[flat]<br>        UpgradeableEvent: UpgradeableComponent::Event,<br>    }<br><br>    #[constructor]<br>    fn constructor(ref self: ContractState,owner: ContractAddress, intial_value: u128) {<br>        self.ownable.initializer(owner);<br>        self.value.write(intial_value );<br>    }<br><br>    #[abi(embed_v0)]<br>    impl TryImpl of super:: ITry&lt;ContractState&gt; {<br>        fn get_value(self: @ContractState)-&gt; u128 {<br>            self.value.read()<br>        }<br><br>        fn increase_value(ref self: ContractState) -&gt; u128{<br>            self.value.write(self.value.read() + 1);<br>            self.value.read()<br>        }<br>        //new function<br>        fn decrease_value(ref self: ContractState) -&gt; u128{<br>            assert(self.value.read() &gt; 0, &#39;number &lt; 0&#39;);<br>            self.value.write(self.value.read() - 1);<br>            self.value.read()<br>        }<br>    }<br><br>   //<br>    // Upgradeable<br>    //<br>    <br>    #[abi(embed_v0)]<br>    impl UpgradeableImpl of IUpgradeable&lt;ContractState&gt; {<br>        fn upgrade(ref self: ContractState, new_class_hash: ClassHash) {<br>            self.ownable.assert_only_owner();<br>            self.upgradeable.upgrade(new_class_hash);<br>        }<br>    }<br>}</pre><h3>Step 10: Update deploymentsOrDeclare.ts and Declare Upgrade</h3><p>Update deploymentsOrDeclare.ts to declare the updated contract:</p><pre>let name = &quot;gammer_v1&quot;;</pre><h3>Step 11: Declare</h3><blockquote>Declare the new contract version, <strong><em>make sure the deployment code is commented before running the command below</em></strong>:</blockquote><pre>scarb build &amp;<br>npm run deploy-gammer</pre><p>A new environment variable is automatically added to your .env file:<br>GAMMER_V1_CLASS_HASH</p><h3>Step 12: Create upgradeContracts.ts</h3><p>Create an upgradeContracts.ts file in the scripts folder with the following content:</p><pre>import { Account, CallData, Contract, RpcProvider, stark } from &quot;starknet&quot;;<br>import { getCompiledCode } from &quot;./utils&quot;;<br><br>import fs from &quot;fs&quot;;<br>import dotenv from &quot;dotenv&quot;;<br><br>dotenv.config({ path: __dirname + &quot;/../.env&quot; });<br><br>const provider = new RpcProvider({<br>  nodeUrl: process.env.RPC_ENDPOINT,<br>});<br><br>// initialize existing predeployed account 0<br>console.log(&quot;ACCOUNT_ADDRESS=&quot;, process.env.DEPLOYER_ADDRESS);<br>console.log(&quot;ACCOUNT_PRIVATE_KEY=&quot;, process.env.DEPLOYER_PRIVATE_KEY);<br>const privateKey0 = process.env.DEPLOYER_PRIVATE_KEY ?? &quot;&quot;;<br>const accountAddress0: string = process.env.DEPLOYER_ADDRESS ?? &quot;&quot;;<br>const owner = new Account(provider, accountAddress0, privateKey0);<br>console.log(&quot;Account connected.\n&quot;);<br><br>async function upgrade() {<br>  const new_class_hash = process.env.GAMMER_V1_CLASS_HASH as string;<br>  const contract_address = process.env.GAMMER_ADDRESS as string;<br><br>  // Declare <br>  let sierraCode, casmCode;<br><br>  try {<br>    ({ sierraCode, casmCode } = await getCompiledCode(&quot;gammer_gammer&quot;));<br>  } catch (error: any) {<br>    console.log(&quot;Failed to read contract files&quot;);<br>    process.exit(1);<br>  }<br><br>  const contract = new Contract(sierraCode.abi, contract_address, owner);<br>  let result = await contract.upgrade(new_class_hash);<br>  console.log(&quot;✅ contract upgraded approved, amount:&quot;, new_class_hash);<br>  console.log(result, result);<br>}<br><br>async function main() {<br>  await upgrade();<br>}<br><br>main();</pre><h3>Step 13: Upgrade the Contract</h3><p>Run the upgrade command:</p><pre>npm run upgrade</pre><h3>Conclusion</h3><p>By leveraging OpenZeppelin’s upgradeable library and snforge, you’ve successfully built, deployed, and upgraded an upgradable contract on StarkNet. Always respect the order of state variables to ensure smooth upgrades. Explore more possibilities with StarkNet’s advanced features!</p><p>Access GitHub repo here : <a href="https://github.com/Muhindo-Galien/starknet-upgredeable-contracts">https://github.com/Muhindo-Galien/starknet-upgredeable-contracts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=033648e2ee96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/building-upgradable-smart-contracts-on-starknet-033648e2ee96">Building Upgradable Smart Contracts on StarkNet</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tokenomics in ERC-4626 Vaults: A Comprehensive Guide]]></title>
            <link>https://medium.com/coinmonks/tokenomics-in-erc-4626-vaults-a-comprehensive-guide-be58a776a403?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/be58a776a403</guid>
            <category><![CDATA[lsd]]></category>
            <category><![CDATA[defi-strategy]]></category>
            <category><![CDATA[defi-vault]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 23:41:45 GMT</pubDate>
            <atom:updated>2024-12-28T17:50:08.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*70MHZ63ekgsAUlkrCXczLw.jpeg" /></figure><p>As decentralized finance (DeFi) evolves, the need for efficient and transparent mechanisms for managing yield-bearing assets has driven the adoption of <strong>ERC-4626</strong>. This tokenized vault standard provides a unified interface for deposits, withdrawals, and yield tracking, making it easier to create and manage yield-bearing vaults. At the heart of ERC-4626 vaults lies <strong>tokenomics</strong>, which governs the financial structure of how value is created, distributed, and accrued within the system.</p><p>This article delves into how ERC-4626 handles share issuance and redemption, the impact of tokenomics on user incentives and vault performance, and examines case studies of well-designed ERC-4626 vaults.</p><h3>Understanding ERC-4626 Vaults</h3><h4>1. Core Concepts of ERC-4626</h4><p>ERC-4626 vaults are designed to simplify and standardize interactions with yield-bearing assets. Users deposit assets (e.g., ETH, DAI) and receive <strong>shares</strong> that represent their proportional ownership of the vault. These shares are redeemable for the underlying assets, and their value grows as the vault generates yield.</p><p>Key features of ERC-4626:</p><ul><li><strong>Share Representation</strong>: Users own shares proportional to their deposits.</li><li><strong>Yield Accumulation</strong>: Vault yield increases the value of the underlying assets, reflected in the share price.</li><li><strong>Composability</strong>: ERC-4626 vaults integrate seamlessly with DeFi protocols, enhancing functionality.</li></ul><h3>How ERC-4626 Handles Share Issuance and Redemption</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*WCQqC8kafOnP50ul5X5rVw.png" /></figure><h4>1. Calculating Shares for Deposits</h4><p>When a user deposits assets, the vault mints shares based on the vault’s current balance and total shares in circulation. The formula ensures proportional ownership for depositors.</p><h4>Formula:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*OXMgkwOC7iBci_x4VY732w.png" /></figure><p>Where:</p><ul><li><strong>a</strong>: Amount to deposit</li><li><strong>B</strong>: Balance of the vault before deposit</li><li><strong>s</strong>: Amount of shares to mint</li><li><strong>T</strong>: Total shares before mint</li></ul><p>The minting process ensures:</p><ul><li>Users depositing larger amounts receive more shares.</li><li>Shares grow in value as the vault generates yield.</li></ul><h4>2. Calculating Shares for Withdrawals</h4><p>When a user withdraws assets, shares are burned to maintain proportional ownership. The redemption is calculated using the following formula:</p><h4>Formula:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*ceB9mGJT5ujvPhEnvzM6ow.png" /></figure><p>Where:</p><ul><li><strong>a</strong>: Amount to withdraw</li><li><strong>B</strong>: Balance of the vault before withdrawal</li><li><strong>s</strong>: Shares to burn</li><li><strong>T</strong>: Total shares before burning</li></ul><p>This formula ensures:</p><ul><li>Users withdrawing more shares receive a higher amount of assets.</li><li>Vault balances remain proportional to the remaining shares.</li></ul><h3>The Impact of Tokenomics on User Incentives and Vault Performance</h3><p>Tokenomics plays a crucial role in shaping user behavior and vault performance. By balancing incentives and sustainability, ERC-4626 vaults can optimize liquidity and yield.</p><h4>1. User Incentives</h4><ul><li><strong>Proportional Rewards</strong>: Share-based tokenomics ensure that users are rewarded proportionally to their contributions.</li><li><strong>Early Entry Benefits</strong>: Early users benefit from lower share prices and higher yield growth.</li><li><strong>Penalty Mechanisms</strong>: Exit fees discourage frequent withdrawals, stabilizing vault liquidity.</li></ul><h4>2. Vault Performance</h4><ul><li><strong>Capital Efficiency</strong>: Optimized share calculations maximize vault capital while maintaining liquidity.</li><li><strong>Sustainability</strong>: Aligning tokenomics with long-term goals prevents unsustainable behaviors.</li><li><strong>Fee Models</strong>: Performance and management fees support protocol maintenance and incentivize developers.</li></ul><h3>Case Studies of Well-Designed ERC-4626 Vaults</h3><h4>1. Yearn Finance</h4><p><strong>Vault Type</strong>: Yield Aggregator<br> <strong>Tokenomics Highlights</strong>:</p><ul><li>Shares minted and burned using a proportional formula similar to ERC-4626 standards.</li><li>Rewards compound automatically, reflecting in share price growth.</li><li>Early users benefit from lower share prices.</li></ul><p><strong>Impact</strong>: Yearn’s tokenomics ensures sustainability and rewards long-term participation, solidifying its position as a leader in DeFi.</p><h4>2. Lido Finance</h4><p><strong>Vault Type</strong>: Liquid Staking Derivatives<br> <strong>Tokenomics Highlights</strong>:</p><ul><li>Stakers receive <strong>stETH</strong> tokens, which increase in value as staking rewards accumulate.</li><li>Share issuance and redemption follow proportional principles to ensure fair allocation.</li><li>Rewards auto-compound, reflected in rising token value.</li></ul><p><strong>Impact</strong>: Lido’s focus on seamless staking and redemption has made it a favorite for ETH staking.</p><h4>3. Aave aTokens</h4><p><strong>Vault Type</strong>: Lending<br> <strong>Tokenomics Highlights</strong>:</p><ul><li>Users receive <strong>aTokens</strong> that grow in value as interest accrues.</li><li>Transparent interest rate models align incentives for both lenders and borrowers.</li><li>ERC-4626 principles enable composable vault design for broader DeFi integration.</li></ul><p><strong>Impact</strong>: Aave’s adoption of ERC-4626-like mechanisms enhances its lending and borrowing ecosystem.</p><h4>Best Practices for ERC-4626 Vault Tokenomics</h4><ol><li><strong>Transparent Share Calculations</strong>: Clearly define deposit and withdrawal formulas to build user trust.</li><li><strong>Align Incentives</strong>: Reward long-term participation and discourage frequent withdrawals.</li><li><strong>Integrate Composability</strong>: Ensure vaults can integrate with other DeFi protocols.</li><li><strong>Implement Risk Management</strong>: Introduce mechanisms to stabilize vault performance during market volatility.</li></ol><h4>Conclusion</h4><p>ERC-4626 vaults revolutionize how DeFi protocols handle yield-bearing assets by introducing standardized and efficient share-based tokenomics. The share issuance and redemption formulas ensure fair allocation, while robust tokenomics optimize user incentives and vault performance. By examining the success of projects like Yearn, Lido, and Aave, it’s evident that ERC-4626 vaults hold the key to a more sustainable and user-friendly DeFi ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be58a776a403" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/tokenomics-in-erc-4626-vaults-a-comprehensive-guide-be58a776a403">Tokenomics in ERC-4626 Vaults: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Automated Market Maker (AMM) Model Similar to Uniswap V1 using Hardhat]]></title>
            <link>https://medium.com/coinmonks/building-an-automated-market-maker-amm-model-similar-to-uniswap-v1-using-hardhat-ad845a68fb67?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad845a68fb67</guid>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[amm]]></category>
            <category><![CDATA[dex]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 15:34:09 GMT</pubDate>
            <atom:updated>2024-04-20T09:20:46.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S946guk5OJwqSmWXtti6Uw.png" /></figure><p>Automated Market Makers (AMMs) have revolutionized decentralized finance (DeFi) by providing a decentralized and automated way to trade tokens. In this tutorial, we will guide you through the process of building a simple AMM model similar to Uniswap V1 using Hardhat and Solidity. The AMM model will allow users to add liquidity, remove liquidity, and swap Olame tokens (OLA) with CELO tokens.</p><h3>Prerequisites</h3><p>Before getting started, make sure you have the following installed:<br>Before we embark on this exciting journey, make sure you have the following prerequisites in place:</p><ol><li>Solid Understanding of Blockchain and Smart Contracts: You should have a solid grasp of blockchain technology and how smart contracts work.</li><li>Ethereum and Hardhat Knowledge: Familiarity with Ethereum and the Hardhat development environment is essential. If you’re new to Hardhat, consider going through their <a href="https://hardhat.org/getting-started/">official documentation</a> first.</li><li>Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your machine.</li></ol><p>Now that we have our prerequisites sorted, let’s get started with setting up our project and diving into the fascinating world of flash loan arbitrage!</p><h3>Setting Up the Project</h3><h3>Step 1: Initialize a New Hardhat Project</h3><p>Open your terminal and navigate to your desired project directory. Run the following commands:</p><pre>npm install --save-dev hardhat<br>npx hardhat</pre><p>Follow the prompts to create a new Hardhat project. Choose the default settings for simplicity.</p><h3>Step 2: Install Dependencies</h3><p>We’ll need to install some additional dependencies for our project. Open your terminal and run the following commands:</p><pre>yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers @nomiclabs/hardhat-etherscan @nomiclabs/hardhat-waffle chai ethereum-waffle hardhat hardhat-contract-sizer hardhat-deploy hardhat-gas-reporter prettier prettier-plugin-solidity solhint solidity-coverage dotenv</pre><h3>Step 3: Project Structure</h3><p>Your project directory should now have the following structure:</p><pre>- contracts/<br>  - Token.sol<br>  - AMM.sol<br>- deploy/<br>  - 00-deployToken.ts<br>  - 01-deployAMM.ts  <br>- scripts/<br>- test/<br>- hardhat.config.ts<br>- package.json<br>- README.md</pre><p>create .env file, add your PRIVATE_KEY by your proper credentials as follows:</p><pre>PRIVATE_KEY=....</pre><p>Open hardhat.config.ts, and update it with the details below:</p><pre>import { HardhatUserConfig } from &quot;hardhat/config&quot;;<br>import &quot;@nomicfoundation/hardhat-toolbox&quot;;<br>require(&quot;@nomiclabs/hardhat-ethers&quot;);<br>require(&quot;@nomiclabs/hardhat-etherscan&quot;);<br><br>import * as dotenv from &quot;dotenv&quot;;<br>dotenv.config();<br><br>const WALLET_PRIVATE_KEY = process.env.PRIVATE_KEY as string;<br><br>const config: HardhatUserConfig = {<br>  solidity: &quot;0.8.17&quot;,<br>  networks: {<br>    hardhat: {<br>    },<br>    alfajores: {<br>      url: &quot;https://alfajores-forno.celo-testnet.org&quot;,<br>      chainId: 44787,<br>      gas: 10000000,<br>      // replace this ox by you private key<br>      accounts: [WALLET_PRIVATE_KEY]<br>    }<br>  },<br>};<br><br>export default config;</pre><h3>Step 4: Writing OlameToken Contract</h3><pre>// contracts/OlameToken.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract OlameToken is ERC20 {<br>    event Faucet(address indexed minter, uint256 amount);<br><br>    uint256 public DEFAULT_MINT_AMOUNT = 1000;<br><br>    constructor() ERC20(&quot;Olame Token&quot;, &quot;OLA&quot;) {}<br><br>    function faucet() public {<br>        uint256 amount = DEFAULT_MINT_AMOUNT * (10 ** decimals());<br>        _mint(msg.sender, amount);<br>        emit Faucet(msg.sender, DEFAULT_MINT_AMOUNT);<br>    }<br>}</pre><p>This contract defines the OlameToken ERC20 token and includes a faucet function to mint tokens for testing.</p><h3>Step 5: Writing AMM Contract</h3><p>Create a new file named AMM.sol in the contracts directory and paste the following content:</p><pre>// contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    // ... (paste the rest of the AMM contract code here)<br>}</pre><p>This file includes the skeleton of the AMM contract. We will add the AMM contract code portion by portion in the following steps.</p><h4>1. Adding Constructor and Initialization</h4><p>Now, let’s add the constructor and initialization code to the AMM contract. Update the AMM.sol file:</p><pre>// contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    /**<br>    * @dev The address of the Olame token contract.<br>    */<br>    address public olameTokenAddress;<br><br>    /**<br>     * @dev Emitted when liquidity is added to the contract.<br>     * @param provider The address of the liquidity provider.<br>     * @param amount The amount of tokens provided.<br>     * @param liquidity The amount of liquidity tokens minted.<br>     */<br>    event LiquidityAdded(address indexed provider, uint256 amount, uint256 liquidity);<br><br>    /**<br>     * @dev Emitted when liquidity is removed from the contract.<br>     * @param provider The address of the liquidity provider.<br>     * @param amount The amount of liquidity tokens burned.<br>     * @param celoAmount The amount of CELO tokens transferred to the provider.<br>     * @param olameTokenAmount The amount of Olame tokens transferred to the provider.<br>     */<br>    event LiquidityRemoved(address indexed provider, uint256 amount, uint256 celoAmount, uint256 olameTokenAmount);<br><br>    /**<br>     * @dev Emitted when tokens are purchased from the contract.<br>     * @param buyer The address of the buyer.<br>     * @param celoAmount The amount of CELO tokens provided.<br>     * @param tokensBought The amount of Olame tokens bought.<br>     */<br>    event TokensPurchased(address indexed buyer, uint256 celoAmount, uint256 tokensBought);<br><br>    /**<br>     * @dev Emitted when tokens are sold to the contract.<br>     * @param seller The address of the seller.<br>     * @param tokensSold The amount of Olame tokens sold.<br>     * @param celoAmount The amount of CELO tokens transferred to the seller.<br>     */<br>    event TokensSold(address indexed seller, uint256 tokensSold, uint256 celoAmount);<br><br><br>    /**<br>     * @dev Initializes the AMM contract.<br>     * @param _olameTokenAddress The address of the Olame token.<br>     */<br>    constructor(address _olameTokenAddress) ERC20(&quot;Olame LP Token&quot;, &quot;OLA-LP&quot;) {<br>        require(_olameTokenAddress != address(0), &quot;Token address passed is a null address&quot;);<br>        olameTokenAddress = _olameTokenAddress;<br>    }<br><br>    // ... (continue with the next steps)<br>}</pre><p>In this step, we added the constructor and declared events for liquidity addition, removal, token purchase, and token sale.</p><h4>2. <strong>Adding Liquidity Functions</strong></h4><p>Now, let’s add the functions responsible for adding liquidity to the AMM. Update the AMM.sol file:</p><pre>// contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    // ... (previous code)<br>    <br>    /**<br>     * @dev Returns the reserve of Olame tokens held by the contract.<br>     * @return The reserve of Olame tokens.<br>     */<br>    function getReserve() public view returns (uint) {<br>        return ERC20(olameTokenAddress).balanceOf(address(this));<br>    }<br><br>    /**<br>     * @dev Adds liquidity to the AMM contract.<br>     * @param _amount The amount of Olame tokens to add.<br>     * @return The amount of liquidity added.<br>     */<br>    function addLiquidity(uint _amount) public payable returns (uint) {<br>        uint liquidity;<br>        uint celoBalance = address(this).balance;<br>        uint olameTokenReserve = getReserve();<br>        ERC20 olameToken = ERC20(olameTokenAddress);<br>        if(olameTokenReserve == 0) {<br>            require(olameToken.transferFrom(msg.sender, address(this), _amount), &quot;Token transfer failed&quot;);<br>            liquidity = celoBalance;<br>            _mint(msg.sender, liquidity);<br>        } else {<br>            uint celoReserve = celoBalance - msg.value;<br>            uint olameTokenAmount = (msg.value * olameTokenReserve)/(celoReserve);<br>            require(_amount &gt;= olameTokenAmount, &quot;Amount of tokens sent is less than the minimum tokens required&quot;);<br>            require(olameToken.transferFrom(msg.sender, address(this), olameTokenAmount), &quot;Token transfer failed&quot;);<br>            liquidity = (msg.value * totalSupply()) / celoReserve;<br>            require(liquidity &gt; 0, &quot;Liquidity amount is zero&quot;);<br>            _mint(msg.sender, liquidity);<br>        }<br>        emit LiquidityAdded(msg.sender, _amount, liquidity);<br>         return liquidity;<br>    }<br><br>    // ... (continue with the next steps)<br>}</pre><p>In this step, we added the getReserve function to retrieve the Olame token reserve and the addLiquidity function for liquidity addition.</p><h4>3. Adding Liquidity Removal Function</h4><p>Now, let’s add the function responsible for removing liquidity from the AMM. Update the AMM.sol file:</p><pre>   // contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    // ... (previous code) /**<br>     * @dev Removes liquidity from the AMM contract.<br>     * @param _amount The amount of LP tokens to remove.<br>     * @return The amount of CELO and Olame tokens received.<br>     */<br>    function removeLiquidity(uint _amount) public returns (uint , uint) {<br>        require(_amount &gt; 0, &quot;LP amount must be greater than zero&quot;);<br>        require(balanceOf(msg.sender) &gt;= _amount, &quot;Insufficient LP tokens to burn&quot;);<br>        uint celoReserve = address(this).balance;<br>        uint _totalSupply = totalSupply();<br>        uint celoAmount = (celoReserve * _amount)/ _totalSupply;<br>        uint olameTokenAmount = (getReserve() * _amount)/ _totalSupply;<br>        _burn(msg.sender, _amount);<br>        payable(msg.sender).transfer(celoAmount);<br>        ERC20(olameTokenAddress).transfer(msg.sender, olameTokenAmount);<br>        emit LiquidityRemoved(msg.sender, _amount, celoAmount, olameTokenAmount);<br>        return (celoAmount, olameTokenAmount);<br>    }<br>}</pre><p>In this step, we added the removeLiquidity function for liquidity removal.</p><h4>4. Adding Token Swap Functions</h4><p>Now, let’s add the functions responsible for swapping CELO for Olame tokens and vice versa. Update the AMM.sol file:</p><pre>// contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    // ... (previous code)<br><br><br>    /**<br>     * @dev Calculates the amount of output tokens for a given input amount and reserves.<br>     * @param inputAmount The input amount of tokens.<br>     * @param inputReserve The input reserve of tokens.<br>     * @param outputReserve The output reserve of tokens.<br>     * @return The amount of output tokens.<br>     */<br>    function getAmountOfTokens(<br>        uint256 inputAmount,<br>        uint256 inputReserve,<br>        uint256 outputReserve<br>    ) public pure returns (uint256) {<br>        require(inputReserve &gt; 0 &amp;&amp; outputReserve &gt; 0, &quot;Invalid reserves&quot;);<br>        uint256 inputAmountWithFee = inputAmount * 99;<br>        uint256 numerator = inputAmountWithFee * outputReserve;<br>        uint256 denominator = (inputReserve * 100) + inputAmountWithFee;<br>        return numerator / denominator;<br>    }<br><br>    /**<br>     * @dev Swaps CELO for Olame tokens.<br>     * @param _minTokens The minimum amount of Olame tokens expected to be received.<br>     */<br>    function celoToOlameToken(uint _minTokens) public payable {<br>        uint256 tokenReserve = getReserve();<br>        <br>        uint256 tokensBought = getAmountOfTokens(<br>            msg.value,<br>            address(this).balance - msg.value,<br>            tokenReserve<br>        );<br><br>        require(tokensBought &gt;= _minTokens, &quot;Insufficient output amount&quot;);<br>        ERC20(olameTokenAddress).transfer(msg.sender, tokensBought);<br>        require(checkTransferSuccess(), &quot;Token transfer failed&quot;);<br>        emit TokensPurchased(msg.sender, msg.value, tokensBought);<br>    }<br>    /**<br>     * @dev Swaps Olame tokens for CELO.<br>     * @param _tokensSold The amount of Olame tokens to sell.<br>     * @param _minCelo The minimum amount of CELO expected to be received.<br>     */<br>    function olameTokenToCelo(uint _tokensSold, uint _minCelo) public {<br>        uint256 tokenReserve = getReserve();<br>        <br>        uint256 celoBought = getAmountOfTokens(<br>            _tokensSold,<br>            tokenReserve,<br>            address(this).balance<br>        );<br>        require(celoBought &gt;= _minCelo, &quot;Insufficient output amount&quot;);<br>        require(<br>            ERC20(olameTokenAddress).transferFrom(<br>                msg.sender,<br>                address(this),<br>                _tokensSold<br>            ),<br>            &quot;Token transfer failed&quot;<br>        );<br>        payable(msg.sender).transfer(celoBought);<br>        emit TokensSold(msg.sender, _tokensSold, celoBought);<br>    }<br><br>    // ... (continue with the next steps)<br>}</pre><p>In this step, we added the getAmountOfTokens function for calculating token swap amounts and the celoToOlameToken and olameTokenToCelo functions for token swaps.</p><h4>5. Completing the Check Transfer Function</h4><p>Finally, let’s add the checkTransferSuccess function to ensure successful token transfers. Update the AMM.sol file:</p><pre>// contracts/AMM.sol<br>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br>    // ... (previous code)<br><br>    /**<br>     * @dev Checks if the token transfer from the contract to itself is successful.<br>     * @return A boolean indicating whether the transfer was successful or not.<br>    */<br>    function checkTransferSuccess() private returns (bool) {<br>    uint256 tokenBalance = ERC20(olameTokenAddress).balanceOf(address(this));<br>    return (tokenBalance == 0 || ERC20(olameTokenAddress).transfer(address(this), tokenBalance));<br>    }<br>}</pre><p>And here’s how the full AMM.solsmart contract should look like:</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.17;<br><br>import &quot;@openzeppelin/contracts/token/ERC20/ERC20.sol&quot;;<br><br>contract AMM is ERC20 {<br><br>    /**<br>    * @dev The address of the Olame token contract.<br>    */<br>    address public olameTokenAddress;<br><br>    /**<br>     * @dev Emitted when liquidity is added to the contract.<br>     * @param provider The address of the liquidity provider.<br>     * @param amount The amount of tokens provided.<br>     * @param liquidity The amount of liquidity tokens minted.<br>     */<br>    event LiquidityAdded(address indexed provider, uint256 amount, uint256 liquidity);<br><br>    /**<br>     * @dev Emitted when liquidity is removed from the contract.<br>     * @param provider The address of the liquidity provider.<br>     * @param amount The amount of liquidity tokens burned.<br>     * @param celoAmount The amount of CELO tokens transferred to the provider.<br>     * @param olameTokenAmount The amount of Olame tokens transferred to the provider.<br>     */<br>    event LiquidityRemoved(address indexed provider, uint256 amount, uint256 celoAmount, uint256 olameTokenAmount);<br><br>    /**<br>     * @dev Emitted when tokens are purchased from the contract.<br>     * @param buyer The address of the buyer.<br>     * @param celoAmount The amount of CELO tokens provided.<br>     * @param tokensBought The amount of Olame tokens bought.<br>     */<br>    event TokensPurchased(address indexed buyer, uint256 celoAmount, uint256 tokensBought);<br><br>    /**<br>     * @dev Emitted when tokens are sold to the contract.<br>     * @param seller The address of the seller.<br>     * @param tokensSold The amount of Olame tokens sold.<br>     * @param celoAmount The amount of CELO tokens transferred to the seller.<br>     */<br>    event TokensSold(address indexed seller, uint256 tokensSold, uint256 celoAmount);<br><br><br>    /**<br>     * @dev Initializes the AMM contract.<br>     * @param _olameTokenAddress The address of the Olame token.<br>     */<br>    constructor(address _olameTokenAddress) ERC20(&quot;Olame LP Token&quot;, &quot;ICB-LP&quot;) {<br>        require(_olameTokenAddress != address(0), &quot;Token address passed is a null address&quot;);<br>        olameTokenAddress = _olameTokenAddress;<br>    }<br><br><br>    /**<br>     * @dev Returns the reserve of Olame tokens held by the contract.<br>     * @return The reserve of Olame tokens.<br>     */<br>    function getReserve() public view returns (uint) {<br>        return ERC20(olameTokenAddress).balanceOf(address(this));<br>    }<br><br>    /**<br>     * @dev Adds liquidity to the AMM contract.<br>     * @param _amount The amount of Olame tokens to add.<br>     * @return The amount of liquidity added.<br>     */<br>    function addLiquidity(uint _amount) public payable returns (uint) {<br>        uint liquidity;<br>        uint celoBalance = address(this).balance;<br>        uint olameTokenReserve = getReserve();<br>        ERC20 olameToken = ERC20(olameTokenAddress);<br>        if(olameTokenReserve == 0) {<br>            require(olameToken.transferFrom(msg.sender, address(this), _amount), &quot;Token transfer failed&quot;);<br>            liquidity = celoBalance;<br>            _mint(msg.sender, liquidity);<br>        } else {<br>            uint celoReserve = celoBalance - msg.value;<br>            uint olameTokenAmount = (msg.value * olameTokenReserve)/(celoReserve);<br>            require(_amount &gt;= olameTokenAmount, &quot;Amount of tokens sent is less than the minimum tokens required&quot;);<br>            require(olameToken.transferFrom(msg.sender, address(this), olameTokenAmount), &quot;Token transfer failed&quot;);<br>            liquidity = (msg.value * totalSupply()) / celoReserve;<br>            require(liquidity &gt; 0, &quot;Liquidity amount is zero&quot;);<br>            _mint(msg.sender, liquidity);<br>        }<br>        emit LiquidityAdded(msg.sender, _amount, liquidity);<br>         return liquidity;<br>    }<br><br>    /**<br>     * @dev Removes liquidity from the AMM contract.<br>     * @param _amount The amount of LP tokens to remove.<br>     * @return The amount of CELO and Olame tokens received.<br>     */<br>    function removeLiquidity(uint _amount) public returns (uint , uint) {<br>        require(_amount &gt; 0, &quot;LP amount must be greater than zero&quot;);<br>        require(balanceOf(msg.sender) &gt;= _amount, &quot;Insufficient LP tokens to burn&quot;);<br>        uint celoReserve = address(this).balance;<br>        uint _totalSupply = totalSupply();<br>        uint celoAmount = (celoReserve * _amount)/ _totalSupply;<br>        uint olameTokenAmount = (getReserve() * _amount)/ _totalSupply;<br>        _burn(msg.sender, _amount);<br>        payable(msg.sender).transfer(celoAmount);<br>        ERC20(olameTokenAddress).transfer(msg.sender, olameTokenAmount);<br>        emit LiquidityRemoved(msg.sender, _amount, celoAmount, olameTokenAmount);<br>        return (celoAmount, olameTokenAmount);<br>    }<br><br>    /**<br>     * @dev Calculates the amount of output tokens for a given input amount and reserves.<br>     * @param inputAmount The input amount of tokens.<br>     * @param inputReserve The input reserve of tokens.<br>     * @param outputReserve The output reserve of tokens.<br>     * @return The amount of output tokens.<br>     */<br>    function getAmountOfTokens(<br>        uint256 inputAmount,<br>        uint256 inputReserve,<br>        uint256 outputReserve<br>    ) public pure returns (uint256) {<br>        require(inputReserve &gt; 0 &amp;&amp; outputReserve &gt; 0, &quot;Invalid reserves&quot;);<br>        uint256 inputAmountWithFee = inputAmount * 99;<br>        uint256 numerator = inputAmountWithFee * outputReserve;<br>        uint256 denominator = (inputReserve * 100) + inputAmountWithFee;<br>        return numerator / denominator;<br>    }<br><br><br>    /**<br>     * @dev Swaps CELO for Olame tokens.<br>     * @param _minTokens The minimum amount of Olame tokens expected to be received.<br>     */<br>    function celoToOlameToken(uint _minTokens) public payable {<br>        uint256 tokenReserve = getReserve();<br>        <br>        uint256 tokensBought = getAmountOfTokens(<br>            msg.value,<br>            address(this).balance - msg.value,<br>            tokenReserve<br>        );<br><br>        require(tokensBought &gt;= _minTokens, &quot;Insufficient output amount&quot;);<br>        ERC20(olameTokenAddress).transfer(msg.sender, tokensBought);<br>        require(checkTransferSuccess(), &quot;Token transfer failed&quot;);<br>        emit TokensPurchased(msg.sender, msg.value, tokensBought);<br>    }<br><br>    /**<br>    * @dev Checks if the token transfer from the contract to itself is successful.<br>    * @return A boolean indicating whether the transfer was successful or not.<br>    */<br>    function checkTransferSuccess() private returns (bool) {<br>    uint256 tokenBalance = ERC20(olameTokenAddress).balanceOf(address(this));<br>    return (tokenBalance == 0 || ERC20(olameTokenAddress).transfer(address(this), tokenBalance));<br>    }<br><br><br>    /**<br>     * @dev Swaps Olame tokens for CELO.<br>     * @param _tokensSold The amount of Olame tokens to sell.<br>     * @param _minCelo The minimum amount of CELO expected to be received.<br>     */<br>    function olameTokenToCelo(uint _tokensSold, uint _minCelo) public {<br>        uint256 tokenReserve = getReserve();<br>        <br>        uint256 celoBought = getAmountOfTokens(<br>            _tokensSold,<br>            tokenReserve,<br>            address(this).balance<br>        );<br>        require(celoBought &gt;= _minCelo, &quot;Insufficient output amount&quot;);<br>        require(<br>            ERC20(olameTokenAddress).transferFrom(<br>                msg.sender,<br>                address(this),<br>                _tokensSold<br>            ),<br>            &quot;Token transfer failed&quot;<br>        );<br>        payable(msg.sender).transfer(celoBought);<br>        emit TokensSold(msg.sender, _tokensSold, celoBought);<br>    }<br>}</pre><p>let’s go through the key functionalities of each contract:</p><h4>OlameToken Contract:</h4><ol><li>Constructor:</li></ol><ul><li>Initializes the OlameToken contract with the name “Olame Token” and symbol “OLA”.</li></ul><p>2. Faucet Function:</p><ul><li>Mints a default amount of Olame Tokens (1000 OLA tokens) to the caller.</li><li>Emits a Faucet event indicating the minter&#39;s address and the amount of tokens minted.</li></ul><h3>AMM Contract:</h3><ol><li><strong><em>Constructor</em></strong>:</li></ol><ul><li>Initializes the AMM contract with the OlameToken contract’s address.</li><li>Requires a non-null OlameToken address to be provided.</li></ul><p>2.<strong><em> getReserve Function:</em></strong></p><ul><li>Returns the current reserve of Olame tokens held by the AMM contract.</li></ul><p>3. <strong><em>addLiquidity Function</em></strong>:</p><ul><li>Allows liquidity providers to add liquidity by providing Olame tokens.</li><li>Computes the corresponding amount of <strong>CELO</strong> tokens to be added based on the current reserves.</li><li>Mints new liquidity tokens <strong>(OLA-LP)</strong> and transfers them to the liquidity provider.</li><li>Emits a LiquidityAdded event indicating the provider&#39;s address, the amount of Olame tokens provided, and the amount of liquidity tokens minted.</li></ul><p>4. <strong>removeLiquidity Function</strong>:</p><ul><li>Allows liquidity providers to remove liquidity by burning their liquidity tokens <strong>(OLA-LP)</strong>.</li><li>Computes the corresponding amounts of CELO and Olame tokens to be returned based on the current reserves and the amount of liquidity tokens burned.</li><li>Transfers the calculated amounts of CELO and Olame tokens to the liquidity provider.</li><li>Emits a LiquidityRemoved event indicating the provider&#39;s address, the amount of liquidity tokens burned, the amount of CELO tokens transferred, and the amount of Olame tokens transferred.</li></ul><p>5. <strong><em>getAmountOfTokens Function:</em></strong></p><ul><li>Calculates the amount of output tokens for a given input amount and reserves, using a simple constant product formula.</li></ul><p>6. <strong><em>celoToOlameToken Function</em></strong>:</p><ul><li>Allows users to swap CELO for Olame tokens.</li><li>Calculates the amount of Olame tokens to be bought based on the input amount of CELO and current reserves.</li><li>Transfers the calculated amount of Olame tokens to the user.</li><li>Emits a TokensPurchased event indicating the buyer&#39;s address, the amount of CELO tokens provided, and the amount of Olame tokens bought.</li></ul><p>7. <strong><em>checkTransferSuccess Function:</em></strong></p><ul><li>Checks if the transfer of Olame tokens from the contract to itself is successful.</li></ul><p>8. <strong><em>olameTokenToCelo Function:</em></strong></p><ul><li>Allows users to swap Olame tokens for CELO.</li><li>Calculates the amount of CELO to be received based on the input amount of Olame tokens and current reserves.</li><li>Transfers the input amount of Olame tokens from the user to the contract and transfers the calculated amount of CELO to the user.</li><li>Emits a TokensSold event indicating the seller&#39;s address, the amount of Olame tokens sold, and the amount of CELO received.</li></ul><p>These contracts together form an Automated Market Maker (AMM) where users can add liquidity, remove liquidity, and swap Olame tokens with CELO and vice versa. The OlameToken contract primarily provides an ERC-20 token (OLA), and the AMM contract facilitates liquidity provision and token swapping.</p><h3>Step 6: Deploying Smart Contracts</h3><p>Deploying your smart contracts is the next crucial step. Let’s take a look at the deployment scripts.</p><p>00-deployToken.js</p><p>The deployment script for the Token.sol contract:</p><pre>import { ethers } from &quot;hardhat&quot;;<br><br>async function main() {<br>  const OlameToken = await ethers.getContractFactory(&quot;OlameToken&quot;);<br>  const token = await OlameToken.deploy();<br><br>  await token.deployed();<br><br>  console.log(<br>    `OlameToken contract deployed to ${token.address}`<br>  );<br>}<br><br>// We recommend this pattern to be able to use async/await everywhere<br>// and properly handle errors.<br>main().catch((error) =&gt; {<br>  console.error(error);<br>  process.exitCode = 1;<br>});<br><br>/*<br>npx hardhat run scripts/deployToken.ts --network alfajores<br>*/</pre><p>01-deployAMM.js</p><p>The deployment script for the AMM.sol contract:</p><pre>import { ethers } from &quot;hardhat&quot;;<br><br>async function main() {<br>  const olameTokenAddress = &quot;0x296d5bF623c2db0F54A373669E64D757C9A2e537&quot;;<br><br>  const AMM = await ethers.getContractFactory(&quot;AMM&quot;);<br>  const amm = await AMM.deploy(olameTokenAddress);<br><br>  await amm.deployed();<br><br>  console.log(<br>    `AMM contract deployed to ${amm.address}`<br>  );<br>}<br><br>// We recommend this pattern to be able to use async/await everywhere<br>// and properly handle errors.<br>main().catch((error) =&gt; {<br>  console.error(error);<br>  process.exitCode = 1;<br>});<br></pre><p>Let’s start by deploying the Token.sol contract:</p><pre>npx hardhat run scripts/deployToken.ts --network alfajores</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yX1WwxSLb9GbdNk7-OF6w.png" /></figure><p>Deployed to CELO Alfajores Testnet</p><ul><li>AMM contract: <a href="https://explorer.celo.org/alfajores/address/0x68988579dF5F1C182Ee292a2561b1D0c2cca1fb7">https://explorer.celo.org/alfajores/address/</a>0xcd6B562a78F1461d7E2246bDd283b91E7B00fa9c</li><li>TOKEN contract: <a href="https://explorer.celo.org/alfajores/address/0x296d5bF623c2db0F54A373669E64D757C9A2e537">https://explorer.celo.org/alfajores/address/</a>0xB3DBb5824d03Dc0A805DC430aC6b14Ba4CE9bE9d</li></ul><h3>Step 5: Testing Smart Contracts (Interact with our AMM on FE)</h3><p>Here are the steps to consider to interacct with out AMM model on the frontend:</p><ol><li>Go to the link below and add celo (alfajores to your Metamask wallet)<br><a href="https://revoke.cash/learn/wallets/add-network/celo-alfajores">https://revoke.cash/learn/wallets/add-network/celo-alfajores</a></li><li>Go to the link below to get some testnet token <br><a href="https://faucet.celo.org/alfajores">https://faucet.celo.org/alfajores</a></li><li>Acces this link to interact with Our DEX in the browser<br><a href="https://o-lame-exchange.vercel.app/">https://o-lame-exchange.vercel.app/</a></li></ol><h3>Conclusion</h3><p>Congratulations! You’ve successfully built a basic Automated Market Maker (AMM) model similar to Uniswap V1 using Solidity and Hardhat. This tutorial covered the step-by-step process of creating and testing the OlameToken and AMM contracts. Feel free to explore further optimizations and enhancements for your AMM model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad845a68fb67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/building-an-automated-market-maker-amm-model-similar-to-uniswap-v1-using-hardhat-ad845a68fb67">Building an Automated Market Maker (AMM) Model Similar to Uniswap V1 using Hardhat</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Aave Flash Loan Arbitrage using Hardhat]]></title>
            <link>https://medium.com/coinmonks/a-completeguide-to-aave-flash-loan-arbitrage-using-hardhat-db5bb88eb4fc?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/db5bb88eb4fc</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[flash-loan]]></category>
            <category><![CDATA[aave]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[flash-loan-arbitrage]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 13:40:00 GMT</pubDate>
            <atom:updated>2026-06-23T23:28:05.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQ-ZOOg_Qhp2RQEYNvLtRw.png" /></figure><p>Are you ready to dive into the world of flash loan arbitrage using Aave and Hardhat? If you’re looking to leverage the power of decentralized finance (DeFi) to profit from price discrepancies, you’re in the right place. In this step-by-step tutorial, we’ll guide you through the process of setting up and executing flash loan arbitrage using the Aave protocol and the Hardhat development environment.</p><figure><img alt="Patrick collins" src="https://cdn-images-1.medium.com/max/852/1*VAqO7SG1tqJOSbHWqSzj2g.png" /></figure><h3>Prerequisites</h3><p>Before we embark on this exciting journey, make sure you have the following prerequisites in place:</p><ol><li>Solid Understanding of Blockchain and Smart Contracts: You should have a solid grasp of blockchain technology and how smart contracts work.</li><li>Ethereum and Hardhat Knowledge: Familiarity with Ethereum and the Hardhat development environment is essential. If you’re new to Hardhat, consider going through their <a href="https://hardhat.org/getting-started/">official documentation</a> first.</li><li>Node.js and npm: Ensure you have Node.js and npm (Node Package Manager) installed on your machine.</li></ol><p>Now that we have our prerequisites sorted, let’s get started with setting up our project and diving into the fascinating world of flash loan arbitrage!</p><h3>Setting Up the Project</h3><h3>Step 1: Initialize a New Hardhat Project</h3><p>Open your terminal and navigate to your desired project directory. Run the following commands:</p><pre>npm install --save-dev hardhat<br>npx hardhat</pre><p>Follow the prompts to create a new Hardhat project. Choose the default settings for simplicity.</p><h3>Step 2: Install Dependencies</h3><p>We’ll need to install some additional dependencies for our project. Open your terminal and run the following commands:</p><pre>yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers @nomiclabs/hardhat-etherscan @nomiclabs/hardhat-waffle chai ethereum-waffle hardhat hardhat-contract-sizer hardhat-deploy hardhat-gas-reporter prettier prettier-plugin-solidity solhint solidity-coverage dotenv<br>yarn add @aave/core-v3</pre><h3>Step 3: Project Structure</h3><p>Your project directory should now have the following structure:</p><pre>- contracts/<br>  - FlashLoanArbitrage.sol<br>  - Dex.sol<br>- deploy/<br>  - 00-deployDex.js<br>  - 01-deployFlashLoanArbitrage.js  <br>- scripts/<br>- test/<br>- hardhat.config.js<br>- package.json<br>- README.md</pre><p>create .env file, add both SEPOLIA_RPC_URL and PRIVATE_KEY by your proper credentials as follows:</p><pre>SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/....<br>PRIVATE_KEY=....</pre><p>Open hardhat.config.js, and update it with the details below:</p><pre>    require(&quot;@nomiclabs/hardhat-waffle&quot;)<br>    require(&quot;hardhat-deploy&quot;)<br>    require(&quot;dotenv&quot;).config()<br><br>    /**<br>     * @type import(&#39;hardhat/config&#39;).HardhatUserConfig<br>     */<br><br>    const SEPOLIA_RPC_URL =<br>        process.env.SEPOLIA_RPC_URL || &quot;https://eth-sepolia.g.alchemy.com/v2/YOUR-API-KEY&quot;<br>    const PRIVATE_KEY = process.env.PRIVATE_KEY || &quot;0x&quot;<br><br>    module.exports = {<br>        defaultNetwork: &quot;hardhat&quot;,<br>        networks: {<br>            hardhat: {<br>                // // If you want to do some forking, uncomment this<br>                // forking: {<br>                //   url: MAINNET_RPC_URL<br>                // }<br>                chainId: 31337,<br>            },<br>            localhost: {<br>                chainId: 31337,<br>            },<br>            sepolia: {<br>                url: SEPOLIA_RPC_URL,<br>                accounts: PRIVATE_KEY !== undefined ? [PRIVATE_KEY] : [],<br>                //   accounts: {<br>                //     mnemonic: MNEMONIC,<br>                //   },<br>                saveDeployments: true,<br>                chainId: 11155111,<br>            },<br>        },<br>        namedAccounts: {<br>            deployer: {<br>                default: 0, // here this will by default take the first account as deployer<br>                1: 0, // similarly on mainnet it will take the first account as deployer. Note though that depending on how hardhat network are configured, the account 0 on one network can be different than on another<br>            },<br>            player: {<br>                default: 1,<br>            },<br>        },<br>        solidity: {<br>            compilers: [<br>                {<br>                    version: &quot;0.8.7&quot;,<br>                },<br>                {<br>                    version: &quot;0.8.10&quot;,<br>                },<br>            ],<br>        },<br>        mocha: {<br>            timeout: 500000, // 500 seconds max for running tests<br>        },<br>    }</pre><p>Additionally, create a new file called helper-hardhat-config.js in the root directory and add the following needed details keeping in ming that we’re using the <strong><em>Sepolia test network</em></strong> for all save addresses:<br>1. PoolAddressesProvider,<br>2. daiAddress,<br>3. usdcAddress</p><p>Here’s how this file should look:</p><pre>const { ethers } = require(&#39;hardhat&#39;);<br><br>const networkConfig = {<br>  default: {<br>    name: &#39;hardhat&#39;,<br>  },<br>  11155111: {<br>    name: &#39;sepolia&#39;,<br>    PoolAddressesProvider: &#39;0x0496275d34753A48320CA58103d5220d394FF77F&#39;,<br>    daiAddress:&#39;0x68194a729C2450ad26072b3D33ADaCbcef39D574&#39;,<br>    usdcAddress:&#39;0xda9d4f9b69ac6C22e444eD9aF0CfC043b7a7f53f&#39;,<br>  },<br>};<br><br>module.exports = {<br>  networkConfig<br>}</pre><p>After all the adjustments made above, here’s how our project structure should look:</p><pre>- contracts/<br>  - FlashLoanArbitrage.sol<br>  - Dex.sol<br>- deploy/<br>  - 00-deployDex.js<br>  - 01-deployFlashLoanArbitrage.js  <br>- scripts/<br>- test/<br>-.env<br>- hardhat.config.js<br>-helper-hardhat-config<br>- package.json<br>- README.md</pre><h3>Step 4: Contracts</h3><p>In this tutorial, we’ll be working with two smart contracts:</p><ol><li>Dex.sol: This contract simulates a decentralized exchange where arbitrage opportunities occur.</li><li>FlashLoanArbitrage.sol: This contract handles flash loans and arbitrage operations.</li></ol><p>Let’s dive into these contracts and understand each line of code. First, we’ll explore FlashLoanArbitrage.sol.</p><p>Dex.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity 0.8.10;<br><br>import {IERC20} from &quot;@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20.sol&quot;;<br><br>contract Dex {<br>    address payable public owner;<br><br>    IERC20 private dai;<br>    IERC20 private usdc;<br><br>    // exchange rate indexes<br>    uint256 dexARate = 90;<br>    uint256 dexBRate = 100;<br><br>    // keeps track of individuals&#39; dai balances<br>    mapping(address =&gt; uint256) public daiBalances;<br><br>    // keeps track of individuals&#39; USDC balances<br>    mapping(address =&gt; uint256) public usdcBalances;<br><br>    constructor(address  _daiAddress, address _usdcAddress) {<br>        owner = payable(msg.sender);<br>        dai = IERC20(_daiAddress);<br>        usdc = IERC20(_usdcAddress);<br>    }<br><br>    function depositUSDC(uint256 _amount) external {<br>        usdcBalances[msg.sender] += _amount;<br>        uint256 allowance = usdc.allowance(msg.sender, address(this));<br>        require(allowance &gt;= _amount, &quot;Check the token allowance&quot;);<br>        usdc.transferFrom(msg.sender, address(this), _amount);<br>    }<br><br>    function depositDAI(uint256 _amount) external {<br>        daiBalances[msg.sender] += _amount;<br>        uint256 allowance = dai.allowance(msg.sender, address(this));<br>        require(allowance &gt;= _amount, &quot;Check the token allowance&quot;);<br>        dai.transferFrom(msg.sender, address(this), _amount);<br>    }<br><br>    function buyDAI() external {<br>        uint256 daiToReceive = ((usdcBalances[msg.sender] / dexARate) * 100) *<br>            (10**12);<br>        dai.transfer(msg.sender, daiToReceive);<br>    }<br><br>    function sellDAI() external {<br>        uint256 usdcToReceive = ((daiBalances[msg.sender] * dexBRate) / 100) /<br>            (10**12);<br>        usdc.transfer(msg.sender, usdcToReceive);<br>    }<br><br>    function getBalance(address _tokenAddress) external view returns (uint256) {<br>        return IERC20(_tokenAddress).balanceOf(address(this));<br>    }<br><br>    function withdraw(address _tokenAddress) external onlyOwner {<br>        IERC20 token = IERC20(_tokenAddress);<br>        token.transfer(msg.sender, token.balanceOf(address(this)));<br>    }<br><br>    modifier onlyOwner() {<br>        require(<br>            msg.sender == owner,<br>            &quot;Only the contract owner can call this function&quot;<br>        );<br>        _;<br>    }<br><br>    receive() external payable {}<br>}</pre><p><strong><em>Read the Dex Contract Explanation:</em></strong></p><p>The Dex.sol contract simulates a decentralized exchange. Let&#39;s dive into its key features:</p><ul><li>Dex Contract: The main contract defines storage variables for the owner, DAI and USDC addresses, and instances of IERC20 for DAI and USDC.</li><li>Token Deposits: depositUSDC and depositDAI functions allow users to deposit USDC and DAI tokens, updating their balances.</li><li>Token Exchange: buyDAI and sellDAI functions simulate token exchanges, buying DAI with USDC and selling DAI for USDC based on exchange rates.</li><li>Balance Tracking: The contract tracks individual user balances for DAI and USDC with mappings.</li><li>Token Withdrawal: The withdraw function enables the contract owner to withdraw tokens from the contract.</li></ul><p>FlashLoanArbitrage.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity 0.8.10;<br><br>import {FlashLoanSimpleReceiverBase} from &quot;@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol&quot;;<br>import {IPoolAddressesProvider} from &quot;@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol&quot;;<br>import {IERC20} from &quot;@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20.sol&quot;;<br><br>interface IDex {<br>    function depositUSDC(uint256 _amount) external;<br><br>    function depositDAI(uint256 _amount) external;<br><br>    function buyDAI() external;<br><br>    function sellDAI() external;<br>}<br><br>contract FlashLoanArbitrage is FlashLoanSimpleReceiverBase {<br>    address payable owner;<br>    // Dex contract address<br>    address private dexContractAddress =<br>        0x81EA031a86EaD3AfbD1F50CF18b0B16394b1c076;<br><br>    IERC20 private dai;<br>    IERC20 private usdc;<br>    IDex private dexContract;<br><br>    constructor(address _addressProvider,address  _daiAddress, address _usdcAddress)<br>        FlashLoanSimpleReceiverBase(IPoolAddressesProvider(_addressProvider))<br>    {<br>        owner = payable(msg.sender);<br><br>        dai = IERC20(_daiAddress);<br>        usdc = IERC20(_usdcAddress);<br>        dexContract = IDex(dexContractAddress);<br>    }<br><br>    /**<br>        This function is called after your contract has received the flash loaned amount<br>     */<br>    function executeOperation(<br>        address asset,<br>        uint256 amount,<br>        uint256 premium,<br>        address initiator,<br>        bytes calldata params<br>    ) external override returns (bool) {<br>        //<br>        // This contract now has the funds requested.<br>        // Your logic goes here.<br>        //<br><br>        // Arbirtage operation<br>        dexContract.depositUSDC(1000000000); // 1000 USDC<br>        dexContract.buyDAI();<br>        dexContract.depositDAI(dai.balanceOf(address(this)));<br>        dexContract.sellDAI();<br><br>        // At the end of your logic above, this contract owes<br>        // the flashloaned amount + premiums.<br>        // Therefore ensure your contract has enough to repay<br>        // these amounts.<br><br>        // Approve the Pool contract allowance to *pull* the owed amount<br>        uint256 amountOwed = amount + premium;<br>        IERC20(asset).approve(address(POOL), amountOwed);<br><br>        return true;<br>    }<br><br>    function requestFlashLoan(address _token, uint256 _amount) public {<br>        address receiverAddress = address(this);<br>        address asset = _token;<br>        uint256 amount = _amount;<br>        bytes memory params = &quot;&quot;;<br>        uint16 referralCode = 0;<br><br>        POOL.flashLoanSimple(<br>            receiverAddress,<br>            asset,<br>            amount,<br>            params,<br>            referralCode<br>        );<br>    }<br><br>    function approveUSDC(uint256 _amount) external returns (bool) {<br>        return usdc.approve(dexContractAddress, _amount);<br>    }<br><br>    function allowanceUSDC() external view returns (uint256) {<br>        return usdc.allowance(address(this), dexContractAddress);<br>    }<br><br>    function approveDAI(uint256 _amount) external returns (bool) {<br>        return dai.approve(dexContractAddress, _amount);<br>    }<br><br>    function allowanceDAI() external view returns (uint256) {<br>        return dai.allowance(address(this), dexContractAddress);<br>    }<br><br>    function getBalance(address _tokenAddress) external view returns (uint256) {<br>        return IERC20(_tokenAddress).balanceOf(address(this));<br>    }<br><br>    function withdraw(address _tokenAddress) external onlyOwner {<br>        IERC20 token = IERC20(_tokenAddress);<br>        token.transfer(msg.sender, token.balanceOf(address(this)));<br>    }<br><br>    modifier onlyOwner() {<br>        require(<br>            msg.sender == owner,<br>            &quot;Only the contract owner can call this function&quot;<br>        );<br>        _;<br>    }<br><br>    receive() external payable {}<br>}</pre><p><strong><em>Read the FlashLoanArbitrage Contract Explanation:</em></strong></p><p>The FlashLoanArbitrage.sol contract is the core of our arbitrage strategy. It utilizes Aave flash loans to execute profitable trades. Let&#39;s break down the key aspects of the contract:</p><ul><li>Imports and Interfaces: Import the required contracts and interfaces from Aave and OpenZeppelin. These include FlashLoanSimpleReceiverBase, IPoolAddressesProvider, and IERC20.</li><li>IDex Interface: Define the interface for the decentralized exchange (DEX) where arbitrage takes place. Methods like depositUSDC, depositDAI, buyDAI, and sellDAI are defined.</li><li>FlashLoanArbitrage Contract: The main contract, inheriting from, initializes addresses and contracts for DAI, USDC, and the DEX. It implements the executeOperation function that executes the arbitrage operation, buying DAI at a lower rate and selling it at a higher rate.</li><li>Flash Loan Execution: The arbitrage operation is executed within the executeOperation function. Funds are deposited, DAI is bought, deposited, and then sold.</li><li>Loan Repayment: The contract repays the flash loan amount plus the premium to Aave by approving the Pool contract to pull the owed amount.</li><li>Flash Loan Request: The requestFlashLoan function initiates the flash loan by calling flashLoanSimple from the POOL contract.</li><li>Token Approval and Allowance: Functions like approveUSDC, approveDAI, allowanceUSDC, and allowanceDAI are included for approving tokens and checking allowances for the DEX.</li><li>Balance Inquiry and Withdrawal: The getBalance function checks the balance of a token. The withdraw function allows the contract owner to withdraw tokens.</li></ul><h3>Step 5: Deploying Smart Contracts</h3><p>Deploying your smart contracts is the next crucial step. Let’s take a look at the deployment scripts.</p><p>00-deployDex.js</p><p>The deployment script for the Dex.sol contract:</p><pre>const { network } = require(&quot;hardhat&quot;)<br>const { networkConfig } = require(&quot;../helper-hardhat-config&quot;)<br><br>module.exports = async ({ getNamedAccounts, deployments }) =&gt; {<br>  const { deploy, log } = deployments<br>  const { deployer } = await getNamedAccounts()<br>  const chainId = network.config.chainId<br>  const arguments = [networkConfig[chainId][&quot;daiAddress&quot;],networkConfig[chainId][&quot;usdcAddress&quot;]]<br><br>  const dex = await deploy(&quot;Dex&quot;, {<br>    from: deployer,<br>    args: arguments,<br>    log: true,<br>  })<br><br>  log(&quot;Dex contract deployed at : &quot;, dex.address)<br>}<br><br>module.exports.tags = [&quot;all&quot;, &quot;dex&quot;]</pre><p>01-deployFlashLoanArbitrage.js</p><p>The deployment script for the FlashLoanArbitrage.sol contract:</p><pre>const { network } = require(&quot;hardhat&quot;)<br>const { networkConfig } = require(&quot;../helper-hardhat-config&quot;)<br><br>module.exports = async ({ getNamedAccounts, deployments }) =&gt; {<br>  const { deploy, log } = deployments<br>  const { deployer } = await getNamedAccounts()<br>  const chainId = network.config.chainId<br>  const arguments = [networkConfig[chainId][&quot;PoolAddressesProvider&quot;],networkConfig[chainId][&quot;daiAddress&quot;],networkConfig[chainId][&quot;usdcAddress&quot;]]<br><br>  const dex = await deploy(&quot;FlashLoanArbitrage&quot;, {<br>    from: deployer,<br>    args: arguments,<br>    log: true,<br>  })<br><br>  log(&quot;FlashLoanArbitrage contract deployed at : &quot;, dex.address)<br>}<br><br>module.exports.tags = [&quot;all&quot;, &quot;FlashLoanArbitrage&quot;]</pre><p>Let’s start by deploying the Dex.sol contract:</p><pre>yarn hardhat deploy --tags dex --network sepolia</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6VrAEHypYkKhv9N3lI1QA.png" /></figure><p>The Dex contract address is “<strong>0x81EA031a86EaD3AfbD1F50CF18b0B16394b1c076</strong>” which is added to the FlashLoanArbitrage contract</p><p>Then we deploy FlashLoanArbitrage.sol by running the command below:</p><pre>yarn hardhat deploy --tags FlashLoanArbitrage --network sepolia</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1YfwLQUYNOuK2OmuzwQpUg.png" /></figure><p>which outputs the FlashLoanArbitrage contract address below:<br>“<strong>0xc30b671E6d94C62Ee37669b229c7Cd9Eab2f7098</strong>”</p><h3>Step 5: Testing Smart Contracts</h3><p>Let’s now text out the contracts using Remix IDE, but to be more specific here’s where the Flash Loan Arbitrage:</p><pre><br>// exchange rate indexes<br>uint256 dexARate = 90;<br>uint256 dexBRate = 100;</pre><p>Here, we <strong>buy </strong><strong>1DAI</strong> <strong>at </strong><strong>0.90</strong> and <strong>sell it at </strong><strong>100.00 </strong>.<br>When coping the code to <strong>Remix IDE</strong>, consider change the imports below in both contracts accordingly:</p><pre>import {IERC20} from &quot;@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20.sol&quot;;<br>import {FlashLoanSimpleReceiverBase} from &quot;https://github.com/aave/aave-v3-core/blob/master/contracts/flashloan/base/FlashLoanSimpleReceiver.sol&quot;;<br>import {IPoolAddressesProvider} from &quot;https://github.com/aave/aave-v3-core/blob/master/contracts/interfaces/IPoolAddressesProvider.sol&quot;;</pre><h3>Add liquidity to Dex.sol:</h3><ol><li><strong>USDC 1500</strong></li><li><strong>DAI 1500</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ckTmB-5AN2dQvnUnsGsFkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*BCTRZN6WQedft75yzfPUfg.png" /></figure><h3>Approve:</h3><ol><li><strong>USDC 1000000000</strong></li><li><strong>DAI 1200000000000000000000</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*aKkfkFWc_IPOWLNKpGhYzA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*mgJ2jOPCPpKPuF3CWan_kg.png" /></figure><h3>Request Loan — USDC (6 decimal):</h3><ol><li><strong>0xda9d4f9b69ac6C22e444eD9aF0CfC043b7a7f53f,1000000000 // 1,000 USDC</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onlh242ClrqZ-P3JktCVQg.png" /></figure><p>Let’s view our transaction on ehterscan</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjiefK_EUQrrWP6p3EwkOQ.png" /></figure><p>Here’s the transtions explanation:</p><ol><li>Transfer <strong>1000 USDC</strong> from the aave LendingPool contract toFlashLoanArbitrage contract,</li><li>Deposit <strong>1000 USDC</strong> from the FlashLoanArbitrage contract to Dex contract,</li><li>Purchase of DAI From Dex contract to FlashLoanArbitrage contract,</li><li>Deposit of the DAI amount in the Dex contract,</li><li>Transfer <strong>1,111.1111 USDC</strong> from Dex contract to FlashLoanArbitrage</li><li>Rapay <strong>1000 USDC + </strong><strong>0.05%</strong> of flashloan fee (<strong>1000.5 USDC</strong>)</li></ol><p>After a successfull tranaction, we’ll chek back our balalnce wich increases up to <strong>110.611100 USDC</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXdVgVo88Jr8oPo5eYemxA.png" /></figure><p>GitHub repository: <a href="https://github.com/Muhindo-Galien/Aave-Flash-Loan-Arbitrage">https://github.com/Muhindo-Galien/Aave-Flash-Loan-Arbitrage</a></p><h3>Conclusion</h3><p>Congratulations! You’ve embarked on an exciting journey to explore flash loan arbitrage using Aave and Hardhat. In this tutorial, you learned how to set up your project, understand smart contracts, deploy them and test them using REMIX IDE. With your newly gained knowledge, you’re now equipped to explore and experiment further in the world of decentralized finance. Happy coding and discovering arbitrage opportunities!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db5bb88eb4fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/a-completeguide-to-aave-flash-loan-arbitrage-using-hardhat-db5bb88eb4fc">A Complete Guide to Aave Flash Loan Arbitrage using Hardhat</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ERC-6551 — Token Bound Accounts]]></title>
            <link>https://medium.com/coinmonks/erc-6551-token-bound-accounts-daa56fbd3769?source=rss-a429d7a167bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/daa56fbd3769</guid>
            <category><![CDATA[erc6551]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[token-bound]]></category>
            <category><![CDATA[smartcontractdevelopment]]></category>
            <category><![CDATA[nft]]></category>
            <dc:creator><![CDATA[Olame Galien Muhindo]]></dc:creator>
            <pubDate>Thu, 08 Jun 2023 10:21:42 GMT</pubDate>
            <atom:updated>2023-06-08T10:36:44.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>ERC-6551 — Token Bound Accounts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nH0nX7lF5GLuP7VaFwRLA.png" /></figure><blockquote><em>The new ERC-6551 standard allows NFTs to essentially be their own wallets, termed “Token Bound Accounts”. TBAs enable NFTs to hold and manage various assets, essentially turning NFTs into dynamic entities rather than static assets. This feature facilitates several applications: composability, where NFTs can bundle related assets for easier management and transfer; on-chain identities, where each NFT has its own digital identity for interacting with decentralized apps; provenance, providing a comprehensive transaction history; and dependency, allowing NFTs to interact independently with other on-chain assets, enhancing their functionality and value</em><strong><em>.</em></strong></blockquote><p><strong>ERC-721</strong>, the token standard that introduced NFTs on Ethereum as unique and verifiable digital assets, has gained significant popularity.</p><p>However, imagine the possibilities if we could transform our ordinary NFTs into comprehensive Ethereum accounts.</p><p>This possibility has become a reality with the introduction of a new token standard called <strong>ERC-6551</strong>. It takes Ethereum NFTs to a whole new level of usefulness and functionality.</p><p>Now, your favorite collectible can directly own assets, interact with web3 apps, and serve as your onchain identity more effectively. We are entering an exciting era, and in this post, we will provide you with a comprehensive overview of the fundamentals of ERC-6551. Let’s dive in!</p><h3><strong>Key points about ERC-6551:</strong></h3><p>- <strong>Enhanced utility</strong>: ERC-6551 expands the range of applications for NFTs, allowing them to function as full-fledged Ethereum accounts.</p><p>- <strong>Direct asset ownership</strong>: Your NFT can now directly possess and manage assets, giving you greater control over your digital possessions.</p><p>- <strong>Web3 app interaction</strong>: With ERC-6551, NFTs can seamlessly interact with web3 applications, opening up new possibilities for engagement and functionality.</p><p>- <strong>Onchain identity</strong>: NFTs now have an improved capacity to serve as onchain identities, enhancing their role in decentralized ecosystems.</p><p>We are excited to explore the potential of ERC-6551 and its implications for the future of NFTs and Ethereum. Let’s continue our journey into this fascinating topic!</p><h3>Exploring the Basics of ERC-6551</h3><h3>Relevance of ERC-6551</h3><p><strong>ERC-6551</strong>, a recently launched token standard on the Ethereum mainnet (May 7th, 2023), offers a significant advancement in the capabilities of ERC-721 NFTs. By enabling NFTs to function as independent smart contract accounts, ERC-6551 <em>enhances their versatility and functionality</em>.</p><h3>The Motivation Behind ERC-6551</h3><p>The motivation for the development of ERC-6551 stems from the increasing use of NFTs as onchain identities. Previously, ERC-721 tokens were <strong>unable to act as agents or possess other onchain assets</strong>, which limited their applicability in real-world scenarios involving non-fungible assets.</p><p>To address this limitation, ERC-6551 empowers each ERC-721 token with the complete functionalities of an Ethereum account while maintaining compatibility with existing ERC-721 contracts. This is achieved by deploying unique smart contract accounts known as “<strong>token bound accounts</strong>” for each ERC-721 token through a permissionless registry.</p><p>It’s important to note that ERC-6551 allows a single NFT to own multiple token bound accounts, offering the ability to contain multiple wallets and more.</p><h3>The Implementation of ERC-6551</h3><p><strong>The ERC-6551 system consists of two primary components:</strong></p><ol><li><strong>Permissionless Registry</strong>: This registry enables the deployment of token bound accounts. It provides a mechanism for creating and managing these accounts, enhancing the capabilities of ERC-721 tokens.</li><li><strong>Standard Interface</strong>: ERC-6551 introduces a standardized interface for interacting with token bound accounts. This interface allows seamless communication with the accounts, enabling various functionalities and operations.</li></ol><p>By combining these elements, ERC-6551 revolutionizes the potential applications and possibilities for <em>ERC-721 NFTs</em>, expanding their role as powerful assets in the Ethereum ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ3ijLBP0lNYmDp0k34UWg.jpeg" /></figure><h3>The Capabilities of ERC-6551</h3><p>The ERC-6551 standard unlocks a wide range of possibilities, enabling ERC-721 NFTs to perform the same functions as a regular Ethereum wallet. While the basics include storing other NFTs and trading ERC20 tokens, there’s so much more to explore!</p><p>Let’s delve into an example to illustrate the potential. Imagine you’ve been accumulating NFT wearables within a cutting-edge web3 game. Instead of holding these items in your conventional Ethereum wallet, you can now store them within an NFT of your choosing, such as your player avatar from the same game. This not only enhances the experience by making it more enjoyable and familiar on a psychological level, but it also opens up intriguing opportunities.</p><blockquote>Consider this scenario: if you decide to move on from the game in the future, you can bundle your player avatar together with the accumulated wearables as a unified entity. Through the power of ERC-6551, you can list this cohesive unit on an NFT marketplace for potential sale. This allows you to offer a comprehensive package to interested buyers, maximizing the value and appeal of your NFT collection.</blockquote><p>ERC-6551 empowers NFT holders to go beyond traditional functionalities, transforming NFTs into dynamic and versatile assets with endless possibilities</p><h3>Expanded Possibilities with ERC-6551</h3><p>The potential applications of ERC-6551 are vast and varied. Here’s another example: projects that focus on <strong>Profile Picture (PFP)</strong> collectibles can leverage the expanded utility of their NFTs by rewarding holders with token bound accounts. They can airdrop incentives and rewards directly to the holders within their collection, further incentivizing engagement and loyalty.</p><p>Furthermore, the ability of ERC-6551 to support multiple token bound accounts and multi-chain token bound accounts introduces additional layers of utility. This opens up new avenues for experimentation and innovation within the NFT space, sparking fresh waves of creativity.</p><h3><strong>Caveats and Safety Considerations</strong></h3><p>It’s important to note a couple of caveats and safety implications related to ERC-6551:</p><ol><li><strong>Compatibility Limitations</strong>: Not all NFT projects are compatible with ERC-6551, particularly those whose smart contracts do not rely on an ownerOf method. For example, CryptoPunks is not supported by the standard.</li><li><strong>Fraud Prevention</strong>: Decentralized marketplaces need to exercise caution to prevent potential scams. One example is a scenario where a user sells an NFT that supposedly contains a specific amount of ETH, only to withdraw the ETH after the sale, leaving the buyer with an empty account. Preventing fraudulent behavior requires vigilance and implementation at the marketplace level or through external smart contracts, as it is not directly addressed by ERC-6551.</li><li><strong>Ownership Cycles</strong>: ERC-6551 introduces the possibility of an NFT being transferred to its own token bound account, rendering all assets within that account permanently inaccessible. This creates an “ownership cycle” that is challenging to prevent onchain due to the infinite search space required. While ERC-6551 does not enforce the prevention of these cycles, it is recommended for applications to implement measures in their interfaces to limit such transfers.</li></ol><h3>The Significance of ERC-6551 in the NFT Space</h3><p>The introduction of ERC-6551 marks a monumental milestone in the world of NFTs, ushering in a new era of possibilities. By transforming NFTs into their own smart contract accounts, ERC-6551 enhances the versatility and functionality of these unique digital assets. It not only expands the capabilities of NFTs but also aligns them more closely with real-world use cases, making them more practical and relatable for users.</p><p>Looking at the bigger picture, we can anticipate a surge in ERC-6551 adoption and an influx of innovative experiments in the coming months. The NFT ecosystem will witness the exploration of the full potential of ERC-6551, unlocking new dimensions of utility and creativity.</p><p>Furthermore, the advent of token bound accounts within NFTs addresses one of the common criticisms faced by NFTs — that they can be easily copied or saved by right-clicking. With token bound accounts, this argument becomes increasingly baseless. While it’s true that you can copy and save a picture, you can’t replicate or save the contents and functionality encapsulated within the NFT itself. This emphasizes the unique value and ownership associated with NFTs, reinforcing their position as truly unique and irreplaceable assets.</p><p>As ERC-6551 continues to shape the NFT landscape, we eagerly anticipate the dynamic developments and groundbreaking innovations that lie ahead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daa56fbd3769" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/erc-6551-token-bound-accounts-daa56fbd3769">ERC-6551 — Token Bound Accounts</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>