<?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"><channel><title><![CDATA[Better Backend]]></title><description><![CDATA[Better Backend is your go-to resource for mastering backend development.]]></description><link>https://blog.aditipolkam.me</link><generator>RSS for Node</generator><lastBuildDate>Thu, 23 Apr 2026 03:17:24 GMT</lastBuildDate><atom:link href="https://blog.aditipolkam.me/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Create Efficient Database Indexes for Optimal Long-Term Performance]]></title><description><![CDATA[When building a database-driven application, especially one that deals with large datasets, efficient indexing is key to maintaining performance as your data grows. Poorly designed indexes can lead to slow queries, bloated storage, and frustrating us...]]></description><link>https://blog.aditipolkam.me/efficient-database-indexes</link><guid isPermaLink="true">https://blog.aditipolkam.me/efficient-database-indexes</guid><category><![CDATA[Databases]]></category><category><![CDATA[SQL]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[indexing]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sun, 06 Oct 2024 15:54:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728229837182/f6746945-167e-4fd7-95a2-41a252a03e5d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When building a database-driven application, especially one that deals with large datasets, efficient indexing is key to maintaining performance as your data grows. Poorly designed indexes can lead to slow queries, bloated storage, and frustrating user experiences. On the other hand, well-planned indexes can drastically improve query performance and reduce database load, ensuring your system scales smoothly over time.</p>
<p>In this post, we’ll dive deep into the importance of indexes, how to create better indexes, and the long-term impact on performance, using a social media application that manages posts as an example.</p>
<h3 id="heading-what-are-indexes">What Are Indexes?</h3>
<p>An <strong>index</strong> is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional storage and maintenance overhead. Think of it like an index in a book—it helps you find the information you need without flipping through every page.</p>
<p>While indexes can speed up read operations (queries), they can slow down write operations (inserts, updates, and deletes) because the index must be updated whenever the data in the table changes.</p>
<h3 id="heading-how-indexes-impact-long-term-performance">How Indexes Impact Long-Term Performance</h3>
<p>As your data grows, simple queries that once ran quickly can become painfully slow. This is where indexing comes into play—by organizing your data in a way that allows the database to find it quickly, you avoid full table scans, which can take exponentially longer as the dataset grows.</p>
<p>In the long run, well-designed indexes ensure:</p>
<ul>
<li><p><strong>Faster query execution</strong>: Even with millions or billions of rows, the database can fetch the required data efficiently.</p>
</li>
<li><p><strong>Reduced server load</strong>: Indexes reduce CPU and I/O operations, meaning the database can serve more queries with the same hardware.</p>
</li>
<li><p><strong>Scalability</strong>: As your application grows, properly indexed databases can handle more users and larger datasets without performance degradation.</p>
</li>
</ul>
<p>However, over-indexing or creating unnecessary indexes can result in:</p>
<ul>
<li><p><strong>Increased storage</strong>: Indexes consume disk space, so it’s important to only index the necessary columns.</p>
</li>
<li><p><strong>Slower writes</strong>: Every time data is written to the table, all relevant indexes must be updated, which can lead to slower inserts and updates.</p>
</li>
</ul>
<p>Now, let's go through an example of designing efficient indexes using a social media posts database.</p>
<h3 id="heading-example-indexing-a-social-media-posts-table">Example: Indexing a Social Media Posts Table</h3>
<p>Note: Using postgres compatible SQL here.</p>
<p>Imagine you’re building a social media platform where users can post content, and the system tracks likes, comments, and shares for each post. You have a table for posts that looks like this:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> posts (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">SERIAL</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    user_id <span class="hljs-keyword">IN</span>,
    <span class="hljs-keyword">content</span> <span class="hljs-built_in">TEXT</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>,
    like_count <span class="hljs-built_in">INT</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-number">0</span>,
    comment_count <span class="hljs-built_in">INT</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-number">0</span>,
    share_count <span class="hljs-built_in">INT</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-number">0</span>
);
</code></pre>
<p>Users typically perform the following operations:</p>
<ol>
<li><p>Retrieve posts made in the last 24 hours, ordered by the number of likes.</p>
</li>
<li><p>Find all posts by a specific user, ordered by the most recent.</p>
</li>
<li><p>Fetch the most popular posts based on likes, comments, or shares, regardless of when they were posted.</p>
</li>
</ol>
<p>Let's walk through how you can index this table for these operations.</p>
<h4 id="heading-1-retrieving-recent-posts-ordered-by-likes">1. Retrieving Recent Posts, Ordered by Likes</h4>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> posts 
<span class="hljs-keyword">WHERE</span> created_at &gt; <span class="hljs-keyword">NOW</span>() - <span class="hljs-built_in">INTERVAL</span> <span class="hljs-string">'1 day'</span> 
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> like_count <span class="hljs-keyword">DESC</span>;
</code></pre>
<p>Without an index, this query will require a full table scan, which means the database has to check every row in the <code>posts</code> table to find the relevant records. As your table grows, this becomes inefficient.</p>
<p><strong>Solution</strong>: Create a composite index on <code>created_at</code> and <code>like_count</code>.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_posts_created_at_like_count 
<span class="hljs-keyword">ON</span> posts (created_at, like_count <span class="hljs-keyword">DESC</span>);
</code></pre>
<ul>
<li><p><strong>Why this index works</strong>: The index allows the database to first filter the rows by <code>created_at</code> (to get posts from the last 24 hours) and then order them by <code>like_count</code> in descending order.</p>
</li>
<li><p><strong>Impact</strong>: This index speeds up retrieval of posts based on recent activity, which is a common query pattern in social media applications.</p>
</li>
</ul>
<h4 id="heading-2-finding-posts-by-a-specific-user">2. Finding Posts by a Specific User</h4>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> posts 
<span class="hljs-keyword">WHERE</span> user_id = <span class="hljs-number">123</span> 
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> created_at <span class="hljs-keyword">DESC</span>;
</code></pre>
<p>If you don’t index <code>user_id</code>, the database will need to scan the entire table to find the posts for user <code>123</code>. Again, this becomes slower as the table grows.</p>
<p><strong>Solution</strong>: Create an index on <code>user_id</code> and <code>created_at</code>.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_posts_user_id_created_at 
<span class="hljs-keyword">ON</span> posts (user_id, created_at <span class="hljs-keyword">DESC</span>);
</code></pre>
<ul>
<li><p><strong>Why this index works</strong>: The index will help the database quickly find all posts by the specified user and then sort them by <code>created_at</code> in descending order.</p>
</li>
<li><p><strong>Impact</strong>: Querying for posts by specific users becomes fast, which is a common use case in most social media apps.</p>
</li>
</ul>
<h4 id="heading-3-fetching-popular-posts-based-on-likes-comments-or-shares">3. Fetching Popular Posts Based on Likes, Comments, or Shares</h4>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> posts 
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> like_count <span class="hljs-keyword">DESC</span>, comment_count <span class="hljs-keyword">DESC</span>, share_count <span class="hljs-keyword">DESC</span>;
</code></pre>
<p>Without an index, this query could potentially scan and sort all rows in the table, which becomes very slow for large datasets.</p>
<p><strong>Solution</strong>: Create a composite index on <code>like_count</code>, <code>comment_count</code>, and <code>share_count</code>.</p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_posts_popularity 
<span class="hljs-keyword">ON</span> posts (like_count <span class="hljs-keyword">DESC</span>, comment_count <span class="hljs-keyword">DESC</span>, share_count <span class="hljs-keyword">DESC</span>);
</code></pre>
<ul>
<li><p><strong>Why this index works</strong>: The index allows the database to directly retrieve posts ordered by their popularity metrics (likes, comments, and shares) without scanning the whole table.</p>
</li>
<li><p><strong>Impact</strong>: This index improves the performance of retrieving posts based on engagement, which is crucial for highlighting popular content.</p>
</li>
</ul>
<h3 id="heading-best-practices-for-creating-indexes">Best Practices for Creating Indexes</h3>
<ol>
<li><p><strong>Index Columns You Query Frequently</strong>: Only index columns that are frequently used in <code>WHERE</code>, <code>ORDER BY</code>, or <code>JOIN</code> clauses. Indexing unnecessary columns wastes storage and increases write overhead.</p>
</li>
<li><p><strong>Use Composite Indexes for Multiple Columns</strong>: If your queries filter by multiple columns or need data ordered by multiple columns, consider composite indexes. However, the order of columns in the index matters—always put the most selective column first.</p>
</li>
<li><p><strong>Monitor and Remove Unused Indexes</strong>: Unused indexes take up space and slow down <code>INSERT</code> and <code>UPDATE</code> operations. Regularly monitor index usage and remove any that are no longer needed.</p>
</li>
<li><p><strong>Understand Indexing Overhead</strong>: Indexes make read operations faster but slow down write operations. Always consider this trade-off when adding an index.</p>
</li>
<li><p><strong>Leverage Partial Indexes for Large Tables</strong>: For very large tables, consider using partial indexes that only index a subset of rows. For example, you could index only the most recent posts:</p>
<pre><code class="lang-sql"> <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_recent_posts
 <span class="hljs-keyword">ON</span> posts (like_count <span class="hljs-keyword">DESC</span>)
 <span class="hljs-keyword">WHERE</span> created_at &gt; <span class="hljs-keyword">NOW</span>() - <span class="hljs-built_in">INTERVAL</span> <span class="hljs-string">'1 month'</span>;
</code></pre>
<p> This index only applies to posts from the last month, making it much smaller and more efficient for certain queries.</p>
</li>
</ol>
<h3 id="heading-long-term-impact-of-good-indexing">Long-Term Impact of Good Indexing</h3>
<p>Efficient indexing ensures your application can handle:</p>
<ul>
<li><p><strong>Scalability</strong>: As your user base grows and data accumulates, well-indexed tables maintain high performance.</p>
</li>
<li><p><strong>Faster Read Operations</strong>: Queries that previously took minutes (or more) on large datasets can be reduced to milliseconds with the right indexes.</p>
</li>
<li><p><strong>Better User Experience</strong>: Users expect real-time or near-instantaneous results, and efficient indexing is key to delivering a responsive experience.</p>
</li>
</ul>
<p>On the flip side, poorly indexed databases can lead to:</p>
<ul>
<li><p><strong>Slow Queries</strong>: Without the right indexes, queries that scan large tables become bottlenecks.</p>
</li>
<li><p><strong>Increased Server Costs</strong>: Slow queries put unnecessary load on the database server, leading to higher cloud costs or the need for expensive hardware upgrades.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Indexes are a powerful tool to ensure the long-term scalability and performance of your application. However, creating efficient indexes requires careful consideration of your query patterns and the trade-offs between read and write performance.</p>
<p>By following best practices and regularly reviewing your indexing strategy, you can build an application that scales gracefully and delivers a great experience to users, even as the underlying data grows.</p>
]]></content:encoded></item><item><title><![CDATA[Building a WhatsApp-Like 'User is Typing..' Feature with Node.js, React and Socket.io]]></title><description><![CDATA[Ever wondered how your favorite chat applications keep you engaged by showing those dynamic "X is typing..." notifications? The magic behind these real-time updates is a blend of seamless frontend design and robust backend communication. What if I to...]]></description><link>https://blog.aditipolkam.me/user-typing-indicator-with-nodejs-react-and-socketio</link><guid isPermaLink="true">https://blog.aditipolkam.me/user-typing-indicator-with-nodejs-react-and-socketio</guid><category><![CDATA[Node.js]]></category><category><![CDATA[SocketIO]]></category><category><![CDATA[React]]></category><category><![CDATA[websockets]]></category><category><![CDATA[chat app]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sun, 29 Sep 2024 10:37:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727423331796/1e28a206-b93d-43f0-b534-072b4ed47caf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ever wondered how your favorite chat applications keep you engaged by showing those dynamic "X is typing..." notifications? The magic behind these real-time updates is a blend of seamless frontend design and robust backend communication. What if I told you that you could build this engaging feature yourself using Node.js and React with <a target="_blank" href="http://Socket.IO">Socket.IO</a>? Let’s dive into how you can implement a real-time "X is typing" feature, making your web application more interactive and user-friendly.</p>
<h3 id="heading-the-magic-behind-real-time-messaging">The Magic Behind Real-Time Messaging</h3>
<p>Imagine you’re in a heated conversation with a friend on a chat app. Suddenly, you see "Sarah is typing..." appear above the text input box. It's a small but powerful feature that enhances the chat experience by providing real-time feedback. But how is this magic achieved?</p>
<p>In this blog, we’ll build a simplified version of this feature using Node.js for our backend and React for our frontend. We’ll leverage Socket.IO, a popular library that enables real-time, bidirectional, and event-based communication between the client and the server.</p>
<p>When building real-time applications like chat platforms or collaborative tools, efficiency and relevance in communication are key. You don’t want every user receiving every notification. For instance, in a messaging app, you wouldn’t want a user from one chat room receiving typing notifications from another chat. This is where <strong>Socket.IO rooms</strong> come into play.</p>
<h3 id="heading-setting-the-scene">Setting the Scene</h3>
<p>Before we dive into the code, let’s set up our environment:</p>
<ol>
<li><p><strong>Node.js</strong> - A powerful JavaScript runtime for server-side programming.</p>
</li>
<li><p><strong>React</strong> - A popular JavaScript library for building user interfaces.</p>
</li>
<li><p><strong>Socket.IO</strong> - A library that enables real-time communication.</p>
</li>
</ol>
<p>Our goal is to create a basic chat interface where users can type messages, and the application will display a "User is typing..." indicator whenever a user is actively typing.</p>
<h4 id="heading-what-are-socketio-rooms">What Are Socket.IO Rooms?</h4>
<p>In simple terms, rooms in Socket.IO allow you to create isolated groups of clients that can communicate with each other without broadcasting to every connected user. When a client joins a room, they are essentially telling the server, “I’m interested in events related to this room.” This way, the server can emit events to a particular group of users without affecting others.</p>
<h3 id="heading-step-1-setting-up-the-backend-nodejs-socketio">Step 1: Setting Up the Backend (Node.js + Socket.IO)</h3>
<p><strong>1.1 Install Dependencies</strong></p>
<p>First, create a new Node.js project and install the necessary dependencies.</p>
<p>Follow <a target="_blank" href="https://blog.aditipolkam.me/setting-up-a-nodejs-server-with-typescript">my previous</a> article to setup a typescript + nodejs server or follow the steps below for a JS one.</p>
<pre><code class="lang-bash">mkdir typing-feature
<span class="hljs-built_in">cd</span> typing-feature
npm init -y
</code></pre>
<p>Install the socket.io package</p>
<pre><code class="lang-bash">npm install express socket.io
</code></pre>
<p><strong>1.2 Create the Server</strong></p>
<p>Create a file called <code>server.js</code> and set up a basic Express server with Socket.IO:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> { createServer } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>);
<span class="hljs-keyword">const</span> { Server } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'socket.io'</span>);

<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">3001</span>;

<span class="hljs-keyword">const</span> server = createServer(app);
<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> Server(server, {
  <span class="hljs-attr">cors</span>: {
    <span class="hljs-attr">origin</span>: <span class="hljs-string">'*'</span>,
    <span class="hljs-attr">methods</span>: [<span class="hljs-string">'GET'</span>, <span class="hljs-string">'POST'</span>],
  },
});

<span class="hljs-comment">// Handle socket events</span>
io.on(<span class="hljs-string">'connection'</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A user connected'</span>, socket.id);

  <span class="hljs-comment">// Join a room for typing events</span>
  socket.on(<span class="hljs-string">'join-room'</span>, <span class="hljs-function">(<span class="hljs-params">roomId</span>) =&gt;</span> {
    socket.join(roomId);
  });

  <span class="hljs-comment">// Handle typing events</span>
  socket.on(<span class="hljs-string">'typing'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${data.roomId}</span> - user with id <span class="hljs-subst">${data.user.id}</span> and <span class="hljs-subst">${data.user.username}</span> is typing`</span>);
    socket.to(data.roomId).emit(<span class="hljs-string">'typing'</span>, data.user);
  });

  socket.on(<span class="hljs-string">'stopped-typing'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${data.roomId}</span> - user with id <span class="hljs-subst">${data.user.id}</span> and <span class="hljs-subst">${data.user.username}</span> stopped typing`</span>);
    socket.to(data.roomId).emit(<span class="hljs-string">'stopped-typing'</span>, data.user);
  });

  <span class="hljs-comment">// Handle disconnection</span>
  socket.on(<span class="hljs-string">'disconnect'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User disconnected:'</span>, socket.id);
  });
});

server.listen(PORT, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${PORT}</span>`</span>);
});
</code></pre>
<p>Explanation:</p>
<ul>
<li><p><code>socket.join(roomId)</code>: The user joins a room specified in the data, this can be a group or a personal chat in our chat application.</p>
</li>
<li><p><code>socket.on('typing')</code>: Listens for a typing event and broadcasts it to everyone in the specified room.</p>
</li>
<li><p><code>socket.on('stopped-typing')</code>: Listens for when the user stops typing and emits the event to the room specified.</p>
</li>
</ul>
<p>Now run the server:</p>
<pre><code class="lang-bash">node server.js
</code></pre>
<h3 id="heading-step-2-setting-up-the-frontend-react-socketio">Step 2: Setting Up the Frontend (React + Socket.IO)</h3>
<p><strong>2.1 Install Dependencies</strong></p>
<p>In a new React project (or an existing one), install <a target="_blank" href="https://www.npmjs.com/package/socket.io-client"><code>socket.io-client</code></a> to communicate with the backend:</p>
<pre><code class="lang-bash">npm install socket.io-client
</code></pre>
<p><strong>2.2 Create a Socket Context</strong></p>
<p>Create a <code>SocketContext.tsx</code> file in <code>src/context</code> to manage the Socket.IO connection globally using React Context:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useContext, useEffect, useState, ReactNode } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> io, { Socket } <span class="hljs-keyword">from</span> <span class="hljs-string">"socket.io-client"</span>;

<span class="hljs-keyword">const</span> SocketContext = createContext(<span class="hljs-literal">undefined</span>);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> useSocket = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> context = useContext(SocketContext);
  <span class="hljs-keyword">if</span> (!context) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"useSocket must be used within a SocketProvider"</span>);
  }
  <span class="hljs-keyword">return</span> context;
};


<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SocketProvider = <span class="hljs-function">(<span class="hljs-params">{ children }</span>)=&gt;</span> {
  <span class="hljs-keyword">const</span> [socket, setSocket] = useState(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> newSocket = io(<span class="hljs-string">"http://localhost:3001"</span>); <span class="hljs-comment">// Connect to the server</span>
    setSocket(newSocket);

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      newSocket.close(); <span class="hljs-comment">// Cleanup when component unmounts</span>
    };
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SocketContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">socket</span> }}&gt;</span>
      {children}
    <span class="hljs-tag">&lt;/<span class="hljs-name">SocketContext.Provider</span>&gt;</span></span>
  );
};
</code></pre>
<p>This creates a <code>SocketProvider</code> that connects to the backend server and provides the socket instance throughout the app.</p>
<p><strong>2.3 Integrate Context in the App</strong></p>
<p>In your <code>App.tsx</code> file, wrap the entire application in the <code>SocketProvider</code> so that all components can access the socket connection:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { SocketProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">"./context/SocketContext"</span>;
<span class="hljs-keyword">import</span> Chat <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Chat"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SocketProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Chat</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">SocketProvider</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p><strong>2.4 Building the Chat Component</strong></p>
<p>Create a <code>Chat.tsx</code> component that handles sending typing events and displays when a user is typing:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useSocket } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/SocketContext"</span>;

<span class="hljs-keyword">const</span> Chat = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { socket } = useSocket();
  <span class="hljs-keyword">const</span> [message, setMessage] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [isTyping, setIsTyping] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [typingUser, setTypingUser] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> userId = <span class="hljs-number">10</span>; <span class="hljs-comment">// Current user ID</span>
  <span class="hljs-keyword">const</span> username = <span class="hljs-string">"starlight"</span>; <span class="hljs-comment">// Current user ID</span>
  <span class="hljs-keyword">const</span> roomId = <span class="hljs-string">"The Lounge"</span>; <span class="hljs-comment">// Room name</span>

  <span class="hljs-comment">// Emit typing event when user types</span>
  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    setMessage(e.target.value);
    socket?.emit(<span class="hljs-string">"typing"</span>, { <span class="hljs-attr">roomId</span>: roomId, <span class="hljs-attr">user</span>: { <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">username</span>: username } , <span class="hljs-attr">typing</span>: <span class="hljs-literal">true</span> });
  };

  <span class="hljs-comment">// Emit stop typing event after 2 seconds of inactivity</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">let</span> typingTimer;
    <span class="hljs-keyword">if</span> (message) {
      typingTimer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        socket?.emit(<span class="hljs-string">"stopped-typing"</span>, { <span class="hljs-attr">roomId</span>: roomId, <span class="hljs-attr">user</span>: { <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">username</span>: username }, <span class="hljs-attr">typing</span>: <span class="hljs-literal">false</span> });
      }, <span class="hljs-number">2000</span>);
    }
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearTimeout</span>(typingTimer);
  }, [message, socket, roomId, userId, username]);

  <span class="hljs-comment">// Listen for typing events</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (!socket) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"socket not availble"</span>);
      <span class="hljs-keyword">return</span>;
    }
    socket?.emit(<span class="hljs-string">"join-room"</span>, roomId);

    socket?.on(<span class="hljs-string">"typing"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      setTypingUser(data.username);
      setIsTyping(<span class="hljs-literal">true</span>);
    });

    socket?.on(<span class="hljs-string">"stopped-typing"</span>, <span class="hljs-function">() =&gt;</span> {
      setTypingUser(<span class="hljs-string">""</span>);
      setIsTyping(<span class="hljs-literal">false</span>);
    });

    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      socket?.off(<span class="hljs-string">"typing"</span>);
      socket?.off(<span class="hljs-string">"stopped-typing"</span>);
    };
  }, [socket]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type your message..."</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{message}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
        /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      {isTyping &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{typingUser} is typing...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Chat;
</code></pre>
<p>Explanation:</p>
<ul>
<li><p>When the user types in the input field, we emit a <code>typing</code> event.</p>
</li>
<li><p>After 2 seconds of inactivity, a <code>stopped-typing</code> event is emitted.</p>
</li>
<li><p>We display <code>username is typing...</code> when receiving typing events from other users.</p>
</li>
</ul>
<h3 id="heading-step-3-testing-the-feature">Step 3: Testing the Feature</h3>
<ol>
<li><p>Run the backend server using <code>node server.js</code>.</p>
</li>
<li><p>Start the React frontend by running <code>npm start</code> in your React project.</p>
</li>
<li><p>Open the chat application in multiple browser tabs to see real-time typing notifications when a user is typing.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727605152447/2aa1bfd8-3a2d-4246-bede-dd4100724866.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-4-connecting-to-sockets-with-dynamic-data-optional">Step 4: Connecting to sockets with dynamic data (optional)</h3>
<p>To make the <strong>React Chat component</strong> more interactive and flexible, we can modify it to accept user inputs for joining a specific room and entering a username before starting to type. This way, users will be able to choose a room and provide their display name, adding a personalized touch to the chat experience.</p>
<p>Here’s how we can modify the original <code>Chat</code> component:</p>
<h3 id="heading-steps-to-modify-the-chat-component">Steps to Modify the Chat Component:</h3>
<h4 id="heading-1-set-up-inputs-for-username-and-room">1. <strong>Set Up Inputs for Username and Room:</strong></h4>
<p>We'll add input fields for the username and room ID. These inputs will be used to customize the room the user joins and the name they use in the chat.</p>
<h4 id="heading-2-use-state-for-user-inputs">2. <strong>Use State for User Inputs:</strong></h4>
<p>We’ll manage the username and room ID using <code>useState</code> so that the user can set them before joining the chat room.</p>
<h4 id="heading-3-trigger-room-join-on-submit">3. <strong>Trigger Room Join on Submit:</strong></h4>
<p>Once the user inputs their name and room, the chat will connect them to the selected room, allowing real-time typing notifications between users in the same room.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// src/components/Chat.tsx</span>

<span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useSocket } <span class="hljs-keyword">from</span> <span class="hljs-string">"./context/SocketContext"</span>;

<span class="hljs-keyword">const</span> Chat = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { socket } = useSocket(); <span class="hljs-comment">// Get the socket from context</span>
  <span class="hljs-keyword">const</span> [message, setMessage] = useState&lt;string&gt;(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [isTyping, setIsTyping] = useState&lt;boolean&gt;(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [typingUser, setTypingUser] = useState&lt;string&gt;(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> [roomId, setRoomId] = useState&lt;string&gt;(<span class="hljs-string">""</span>); <span class="hljs-comment">// Input for room</span>
  <span class="hljs-keyword">const</span> [username, setUsername] = useState&lt;string&gt;(<span class="hljs-string">""</span>); <span class="hljs-comment">// Input for username</span>
  <span class="hljs-keyword">const</span> [userId] = useState&lt;number&gt;(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">10000</span>)); <span class="hljs-comment">// Generate random user ID</span>
  <span class="hljs-keyword">const</span> [hasJoined, setHasJoined] = useState&lt;boolean&gt;(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Track if user has joined the room</span>

  <span class="hljs-comment">// Emit typing event when user types</span>
  <span class="hljs-keyword">const</span> handleInputChange = <span class="hljs-function">(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
    setMessage(e.target.value);
    <span class="hljs-keyword">if</span> (socket &amp;&amp; hasJoined) {
      socket.emit(<span class="hljs-string">"typing"</span>, {
        roomId,
        <span class="hljs-attr">user</span>: {
          <span class="hljs-attr">id</span>: userId,
          username,
          <span class="hljs-attr">typing</span>: <span class="hljs-literal">true</span>,
        },
      });
    }
  };

  <span class="hljs-comment">// Emit stop typing after a delay</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">let</span> typingTimer: ReturnType&lt;<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">setTimeout</span>&gt;;
    <span class="hljs-keyword">if</span> (message) {
      typingTimer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (socket &amp;&amp; hasJoined) {
          socket.emit(<span class="hljs-string">"stopped-typing"</span>, {
            roomId,
            <span class="hljs-attr">user</span>: {
              <span class="hljs-attr">id</span>: userId,
              username,
              <span class="hljs-attr">typing</span>: <span class="hljs-literal">false</span>,
            },
          });
        }
      }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Stop typing after 2 seconds</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearTimeout</span>(typingTimer);
  }, [message, socket, roomId, username, userId, hasJoined]);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (!socket) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Socket not available"</span>);
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">if</span> (hasJoined) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Socket available, joining room:"</span>, roomId);
      socket.emit(<span class="hljs-string">"join-room"</span>, roomId);

      <span class="hljs-comment">// Listen for typing events</span>
      socket.on(<span class="hljs-string">"typing"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"caught event typing:"</span>, data);
        setTypingUser(data.username);
        setIsTyping(<span class="hljs-literal">true</span>);
      });

      <span class="hljs-comment">// Listen for stop typing events</span>
      socket.on(<span class="hljs-string">"stopped-typing"</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"caught event stopped-typing:"</span>, data);
        setTypingUser(<span class="hljs-string">""</span>);
        setIsTyping(<span class="hljs-literal">false</span>);
      });

      <span class="hljs-comment">// Cleanup listeners when component unmounts</span>
      <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"closing sockets"</span>);
        socket.off(<span class="hljs-string">"typing"</span>);
        socket.off(<span class="hljs-string">"stopped-typing"</span>);
      };
    }
  }, [socket, hasJoined, roomId]);

  <span class="hljs-keyword">const</span> handleJoin = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">if</span> (username &amp;&amp; roomId) {
      setHasJoined(<span class="hljs-literal">true</span>);
    } <span class="hljs-keyword">else</span> {
      alert(<span class="hljs-string">"Please enter a valid username and room."</span>);
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {!hasJoined ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter username"</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setUsername(e.target.value)}
          /&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>

          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter room to join"</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{roomId}</span>
            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setRoomId(e.target.value)}
          /&gt;

          <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">br</span> /&gt;</span>

          <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleJoin}</span>&gt;</span>Join Chat<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      ) : (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
            Joined room <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{roomId}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> as <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>{username}<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
            <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
            <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type your message..."</span>
            <span class="hljs-attr">value</span>=<span class="hljs-string">{message}</span>
            <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
            <span class="hljs-attr">disabled</span>=<span class="hljs-string">{!hasJoined}</span>
          /&gt;</span>
          {isTyping &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{typingUser} is typing...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      )}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Chat;
</code></pre>
<p><strong>Testing</strong></p>
<ol>
<li><p>Enter username and room to join and click on join chat.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727605919693/a816037f-3f52-4d62-ac1f-b4afbe6e2835.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Do the same from another browser tab</p>
</li>
<li><p>Check result after you start typing in one tab.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727606159335/fa4850a4-de07-4aec-975a-15a95d804302.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>With this setup, you've implemented a real-time "user is typing" feature using Node.js, Socket.IO, and React. This feature creates an interactive chat experience and can be further expanded with more room functionality or personalized notifications for better user interaction.</p>
<p>Happy coding! 🎉</p>
]]></content:encoded></item><item><title><![CDATA[Node.js Architecture: Handling Non-Blocking I/O for Seamless Concurrent Request]]></title><description><![CDATA[Imagine this: You’re navigating your favorite app, maybe checking the latest posts or managing tasks, and everything is running smoothly. Ever wondered what’s happening behind the scenes? How does clicking a button result in instant responses, real-t...]]></description><link>https://blog.aditipolkam.me/nodejs-architecture</link><guid isPermaLink="true">https://blog.aditipolkam.me/nodejs-architecture</guid><category><![CDATA[Node.js]]></category><category><![CDATA[event-driven-architecture]]></category><category><![CDATA[v8 engine]]></category><category><![CDATA[libuv]]></category><category><![CDATA[APIs]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sat, 21 Sep 2024 12:11:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726738019133/fe283c6a-7307-4e84-aab7-a7d64acf21f8.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Imagine this: You’re navigating your favorite app, maybe checking the latest posts or managing tasks, and everything is running smoothly. Ever wondered what’s happening behind the scenes? How does clicking a button result in instant responses, real-time updates, or seamless data fetching? While many might immediately think of JavaScript in the browser, there's a silent workhorse in the background making it all possible - <strong>Node.js</strong>.</p>
<p>But what is Node.js exactly? How does it power so many applications, from chat services to full-blown server-side apps? Let’s dive into the intriguing mechanics that make Node.js such a revolutionary runtime.</p>
<h3 id="heading-javascript-beyond-the-browser"><strong>JavaScript Beyond the Browser</strong></h3>
<p>Historically, JavaScript was confined to browsers, giving life to dynamic web pages. But developers wanted more—JavaScript everywhere! Enter <strong>Node.js</strong>, a runtime that enables JavaScript to run on servers, beyond just browsers. It is cross-platform (built for various operating systems), and open-source. Suddenly, you could use the same language for both the front and back ends of your application. But what makes Node.js different from other server-side technologies like Python, PHP, or Ruby?</p>
<h3 id="heading-event-driven-architecture-the-heartbeat-of-nodejs"><strong>Event-Driven Architecture: The Heartbeat of Node.js</strong></h3>
<p>The magic behind this asynchronous nature lies in its <strong>event-driven architecture</strong>. Think of it like a restaurant kitchen: chefs (the event loop) prepare dishes (tasks) when ingredients (data) arrive. If a dish takes time to cook, they don’t just wait—they start another dish. Once the slow-cooking dish is done, they pick up right where they left off.</p>
<p>In Node.js, this is managed by the <strong>Event Loop</strong>, which handles incoming requests, assigns tasks to the appropriate workers (like reading from a file system or fetching data from a database), and then waits for their completion while continuing to handle other incoming requests.</p>
<h3 id="heading-understanding-the-core-v8-engine-and-the-power-of-asynchronous-io"><strong>Understanding the Core: V8 Engine and the Power of Asynchronous I/O</strong></h3>
<p>Node.js has three critical components that work together to execute JavaScript code efficiently on the server:</p>
<p><strong>1. V8 Engine</strong></p>
<p>At its core, Node.js uses Google’s <strong>V8 engine</strong>, the same engine that powers Chrome, to execute JavaScript. But Node.js does more than just provide a space for running JavaScript—it brings a game-changing feature: <strong>asynchronous, non-blocking I/O</strong>.</p>
<p>In simpler terms, Node.js doesn’t wait. While other programming languages often pause (or "block") when performing actions like accessing a database or reading files, Node.js keeps moving, handling multiple tasks simultaneously. This feature allows it to handle thousands of concurrent connections with minimal overhead, making it perfect for high-traffic apps like streaming platforms or real-time chat services.</p>
<p>Developed by Google for Chrome, V8 compiles JavaScript to machine code, ensuring it runs at lightning speed. It consists of two main parts:</p>
<ul>
<li><p><strong>Memory Heap</strong>: A large, unstructured region of memory where objects, variables, and functions are stored. This heap helps manage dynamic memory allocation during runtime.</p>
</li>
<li><p><strong>Call Stack</strong>: A structured data stack that keeps track of the execution order of functions. Whenever a function is invoked, it gets added to the top of the stack. Once the function is executed, it gets removed, maintaining a clear order of execution.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726665609948/428ee4d1-054a-49c3-a3b3-892c844275f5.png" alt class="image--center mx-auto" /></p>
<p>Since <strong>JavaScript is single-threaded</strong>, there is only one call stack, meaning the code executes sequentially, one function at a time. So, how does Node.js handle concurrent requests efficiently without getting blocked by slow operations like file reading or database access?</p>
<p><strong>2. Libuv</strong></p>
<p>Libuv is a C-based library that provides Node.js with its <strong>asynchronous, non-blocking I/O</strong> capabilities. Bindings are created to connect JavaScript functions to their actual implementations in Libuv, allowing JavaScript to interface with lower-level system operations. While JavaScript is single-threaded, Node.js can handle multiple operations simultaneously due to Libuv.</p>
<p>While JavaScript itself is single-threaded, Libuv delegates long-running tasks (like file system access or networking) to a pool of background threads. These threads work independently, allowing the Node.js main thread (the event loop) to continue processing other requests without waiting for blocking operations to complete. Once the task in the thread pool finishes, the result is passed back to the event loop for further processing.</p>
<p><strong>3. Event Loop</strong></p>
<p>The <strong>Event Loop</strong> is Node.js’s core mechanism that enables asynchronous programming, and it starts running as soon as Node.js begins executing a program. For asynchronous functions, once they start processing, they usually have instructions that need to be executed after they finish. These instructions are placed in a <strong>callback queue</strong>, which operates in a <strong>First In, First Out (FIFO)</strong> manner.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1726721654003/12692804-c501-4947-8568-893049155db5.png" alt class="image--center mx-auto" /></p>
<p>The Event Loop continuously monitors the <strong>call stack</strong> to determine what function to execute next. When the call stack is empty, the event loop picks up tasks from the callback queue, such as I/O operations or timers, and pushes them onto the stack for execution.</p>
<p>This combination of <strong>single-threaded execution</strong> with <strong>non-blocking, asynchronous operations</strong> allows Node.js to efficiently handle <strong>concurrent requests</strong> with high scalability, ensuring that tasks are processed without blocking the main thread.</p>
]]></content:encoded></item><item><title><![CDATA[Setting up a NodeJs server with Typescript]]></title><description><![CDATA[A beginner's guide to set up a Node Server with TypeScript, Eslint, and Prettier.
If you have arrived here in search of TypeScript setup for your nodejs project, this comprehensive guide should help you get started on your journey to building robust ...]]></description><link>https://blog.aditipolkam.me/setting-up-a-nodejs-server-with-typescript</link><guid isPermaLink="true">https://blog.aditipolkam.me/setting-up-a-nodejs-server-with-typescript</guid><category><![CDATA[Node.js]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Tutorial]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Prettier]]></category><category><![CDATA[eslint]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Tue, 16 Jul 2024 17:15:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726738140414/6f7f8e00-baa3-4c33-8400-338183418fc5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A beginner's guide to set up a Node Server with TypeScript, Eslint, and Prettier.</p>
<p>If you have arrived here in search of TypeScript setup for your nodejs project, this comprehensive guide should help you get started on your journey to building robust and maintainable Node.js applications with TypeScript.</p>
<h3 id="heading-step-0-installing-nodejs">Step 0: Installing NodeJS</h3>
<p>Download or upgrade to the latest version of Node.</p>
<h3 id="heading-step-1-initialize-your-project">Step 1: Initialize Your Project</h3>
<p>To get started, create a new Node.js project by running the following command:</p>
<pre><code class="lang-bash">yarn init -y
</code></pre>
<p>This command generates a <code>package.json</code> file with default settings.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"nodejs-api"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
      <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
}
</code></pre>
<p>We will make some adjustments to it later.</p>
<h3 id="heading-step-2-use-commonjs-modules"><strong>Step 2: Use CommonJS Modules</strong></h3>
<p>CommonJS and ES modules are two different ways of importing and exporting modules in JavaScript. CommonJS, historically used in Node.js, relies on the <code>require</code> function for importing modules and <code>module.exports</code> for exporting them. In contrast, ES modules, introduced in ES6, use <code>import</code> and <code>export</code> statements. This distinction impacts how code is structured and dependencies are handled in their respective environments. CommonJS has been the standard in Node.js for a long time, while ES modules (ECMAScript modules) offer native support for modules in JavaScript.</p>
<p>Since we are using TypeScript, which compiles to CommonJS by default, we do not need to enable "type: module" in our <code>package.json</code> file. This allows us to continue using CommonJS syntax without changing the module system. The package.json file looks like this until now:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"nodejs-api"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
       <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"ISC"</span>,
}
</code></pre>
<h3 id="heading-step-3-install-typescript">Step 3: Install TypeScript</h3>
<p>Install TypeScript as a development dependency using the following command:</p>
<pre><code class="lang-bash">yarn add -D typescript
</code></pre>
<h3 id="heading-step-4-configure-typescript">Step 4: Configure TypeScript</h3>
<p>Create a <code>tsconfig.json</code> file to configure TypeScript. This file specifies how TypeScript should transpile your code. Here's a breakdown of the key options in the <code>tsconfig.json</code> file:</p>
<ul>
<li><p><code>"type": "module"</code>: Specifies the module system used by Node.js.</p>
</li>
<li><p><code>"esModuleInterop": true</code>: Enables compatibility between CommonJS and ES Modules.</p>
</li>
<li><p><code>"target": "es2021"</code>: Sets the ECMAScript version to target.</p>
</li>
<li><p><code>"moduleResolution": "node"</code>: Configures how TypeScript resolves module imports.</p>
</li>
<li><p><code>"sourceMap": true</code>: Generates source maps for better debugging.</p>
</li>
<li><p><code>"outDir": "dist"</code>: Specifies the output directory for transpiled code.</p>
</li>
<li><p><code>"strict": true</code>: Enforces strict type checking.</p>
</li>
<li><p><code>"include"</code> and <code>"exclude"</code>: Define which files to include and exclude from TypeScript compilation.</p>
</li>
<li><p><code>"lib": ["es2021"]</code>: Specifies the libraries available in your TypeScript project.</p>
</li>
</ul>
<p>Here's the <code>tsconfig.json</code>:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"module"</span>: <span class="hljs-string">"commonjs"</span>,
    <span class="hljs-attr">"esModuleInterop"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"target"</span>: <span class="hljs-string">"es2021"</span>,
    <span class="hljs-attr">"moduleResolution"</span>: <span class="hljs-string">"node"</span>,
    <span class="hljs-attr">"sourceMap"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"outDir"</span>: <span class="hljs-string">"./dist"</span>,
    <span class="hljs-attr">"strict"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-comment">//"skipLibCheck": true,              </span>
    <span class="hljs-comment">//"noImplicitAny": true,  </span>
    <span class="hljs-comment">//"strictNullChecks": true,</span>
    <span class="hljs-comment">//"strictFunctionTypes": true,</span>
    <span class="hljs-comment">//"noImplicitReturns": true </span>
  },
  <span class="hljs-attr">"include"</span>: [<span class="hljs-string">"src/**/*.ts"</span>, <span class="hljs-string">"index.ts"</span>],
  <span class="hljs-attr">"exclude"</span>: [<span class="hljs-string">"node_modules"</span>],
  <span class="hljs-attr">"lib"</span>: [<span class="hljs-string">"es2021"</span>]
}
</code></pre>
<p>You can optionally create tsconfig.json using the command <code>npx tsc --init</code> which will create it with various options available and you can choose which to keep, like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721147843721/1468d1d4-1e60-4a18-b8e1-357611112753.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-step-5-install-express">Step 5: Install Express</h3>
<p>You can use the popular Express.js framework to build your Node.js server. Install it using the following command:</p>
<pre><code class="lang-bash">yarn add express
</code></pre>
<h3 id="heading-step-6-create-your-typescript-entry-file">Step 6: Create Your TypeScript Entry File</h3>
<p>Create <code>src</code> directory and add an <code>index.ts</code> file it to serve as the entry point for your application:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">"express"</span>;

<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>;

app.get(<span class="hljs-string">"/"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">"Hello, TypeScript Node.js Server!"</span>);
});

app.listen(port, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is running on port <span class="hljs-subst">${port}</span>`</span>);
});
</code></pre>
<h3 id="heading-step-7-install-typesexpress-and-typesnode">Step 7: Install @types/express and @types/node</h3>
<p>Since TypeScript needs type definitions for external packages, importing express will give an error so install <code>@types/express</code>:</p>
<pre><code class="lang-bash">yarn add -D @types/express @types/node
</code></pre>
<p>This package provides TypeScript type declarations for Express.js.</p>
<h3 id="heading-step-8-setting-up-development-scripts">Step 8: Setting Up Development Scripts</h3>
<p>For a smoother development experience, install <code>nodemon</code> as a global package.</p>
<p>Nodemon is a utility for Node.js that automatically restarts the server when changes are detected in the code. It's commonly used during development to streamline the development process by eliminating the need to manually restart the server after every code change. This tool significantly enhances the development workflow, allowing developers to focus on writing code without the interruption of restarting the server repeatedly. You will also need to install ts-node which is a Typescript execution engine.</p>
<pre><code class="lang-bash">yarn add nodemon ts-node -g
</code></pre>
<p>Then, update your <code>package.json</code> file to include scripts for starting your server in development mode:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"nodemon src/index.ts"</span>
}
</code></pre>
<p>Now, you can run your server with <code>yarn dev</code> and it will automatically restart when you make changes to your TypeScript code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721148245338/f6723a62-77dc-49e6-bfc6-a5ef9b021549.png" alt class="image--center mx-auto" /></p>
<p>Let's also add scripts to build and start our application, <code>yarn build</code> will compile all your typescript files into javascript and store in the 'dist' directory as specified in the tsconfig.json.</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  <span class="hljs-attr">"build"</span>: <span class="hljs-string">"tsc"</span>,
  <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node dist/index.js"</span>,
}
</code></pre>
<p>After the build is succeeded, you can run <code>yarn start</code> to start your application.</p>
<h3 id="heading-step-9-adding-eslint-for-code-quality">Step 9: Adding ESLint for Code Quality</h3>
<p>ESLint is a popular static code analysis tool for identifying problematic patterns found in JavaScript code. It helps ensure that your code follows best practices, conforms to coding standards, and avoids common errors.</p>
<p>Developers use ESLint to enforce coding styles and conventions within a project, making the codebase more consistent and readable. It can catch bugs, potential runtime errors, and even detect suspicious code that might lead to unexpected behaviors. Additionally, ESLint can be customized with various plugins and configurations to suit the specific needs and preferences of a project or development team.</p>
<p>Install ESLint and TypeScript-specific ESLint packages:</p>
<pre><code class="lang-bash">yarn add -D eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser
</code></pre>
<p>Create an <code>.eslintrc.json</code> file in your project directory:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"env"</span>: {
    <span class="hljs-attr">"node"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"es2021"</span>: <span class="hljs-literal">true</span>
  },
  <span class="hljs-attr">"extends"</span>: [
    <span class="hljs-string">"eslint:recommended"</span>,
    <span class="hljs-string">"plugin:@typescript-eslint/recommended"</span>
  ],
  <span class="hljs-attr">"parser"</span>: <span class="hljs-string">"@typescript-eslint/parser"</span>,
  <span class="hljs-attr">"parserOptions"</span>: {
    <span class="hljs-attr">"ecmaVersion"</span>: <span class="hljs-number">2021</span>,
    <span class="hljs-attr">"sourceType"</span>: <span class="hljs-string">"module"</span>
  },
  <span class="hljs-attr">"plugins"</span>: [
    <span class="hljs-string">"@typescript-eslint"</span>
  ],
  <span class="hljs-attr">"rules"</span>: {}
}
</code></pre>
<p>Add a lint script in the package.json,</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
    <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint index.ts &amp;&amp; eslint src/**/*.ts"</span>,
}
</code></pre>
<h3 id="heading-step-10-adding-prettier-for-code-formatting">Step 10: Adding Prettier for Code Formatting</h3>
<p>Prettier is a code formatting tool that automatically adjusts the layout and style of your code to follow a consistent and predefined set of rules. It helps maintain a uniform code style across a project by automatically formatting the code according to the configured guidelines. Prettier is commonly used in development environments to ensure that code is easy to read, consistent, and visually appealing, which in turn enhances collaboration and maintains a clean codebase.</p>
<p>Install it:</p>
<pre><code class="lang-bash">yarn add -D prettier
</code></pre>
<p>Create a <code>.prettierrc</code> file in your project directory with your preferred formatting rules:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"semi"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"trailingComma"</span>: <span class="hljs-string">"all"</span>,
  <span class="hljs-attr">"singleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"printWidth"</span>: <span class="hljs-number">120</span>,
  <span class="hljs-attr">"tabWidth"</span>: <span class="hljs-number">2</span>
}
</code></pre>
<p>Add a script to format your code:</p>
<pre><code class="lang-json"><span class="hljs-string">"pretty"</span>: <span class="hljs-string">"prettier --write \"src/**/*.ts\""</span>
</code></pre>
<p>Now, you can run <code>yarn pretty</code> to format your TypeScript files in the src directory of your project.</p>
<p>To build and start your application run <code>yarn build</code> and <code>yarn start</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1721149117083/c6f10a74-def2-4646-b71a-31ba1ee780a4.png" alt class="image--center mx-auto" /></p>
<p>Congratulations! You've successfully set up a Node.js server with TypeScript, added linting with ESLint, code formatting with Prettier. Happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[7 lessons I learned as a college student in tech]]></title><description><![CDATA[Currently, I am employed as a Software Engineer at a startup called The Social Continent. However, approximately 6 years ago, I embarked on my journey into the world of technology as a student, opting to pursue a diploma in Computer Engineering. At t...]]></description><link>https://blog.aditipolkam.me/lessons-i-learned-as-a-college-student-in-tech</link><guid isPermaLink="true">https://blog.aditipolkam.me/lessons-i-learned-as-a-college-student-in-tech</guid><category><![CDATA[General Programming]]></category><category><![CDATA[coding journey]]></category><category><![CDATA[software development]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[College]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Mon, 28 Aug 2023 10:45:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693139731822/4131c181-f989-4925-be87-31a3b8023b8f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Currently, I am employed as a Software Engineer at a startup called The Social Continent. However, approximately 6 years ago, I embarked on my journey into the world of technology as a student, opting to pursue a diploma in Computer Engineering. At the outset of this journey, I experienced a mix of emotions, including confusion, excitement, and apprehension.</p>
<p>Having secured a remarkable 95.20% in my Std X boards, I found myself enrolled at Government Polytechnic Pune. At that time, I had little clarity about my career path. Through a combination of setbacks and achievements, I navigated my way forward. Reflecting on my progress, I often wonder about the series of events that led me to my present position. Starting my diploma without a clear plan, but ending up with a clear vision after completing my bachelor's degree this year, has been an incredible journey. I want to share all the lessons I've learned along the way to make your life in college easier.</p>
<p>My journey began with my first year of diploma studies. During this time, we delved into the fundamentals of programming, starting with the C language. As time marched on, I encountered a significant realization that left a lasting impact.👇</p>
<blockquote>
<p>Embrace the courage to attempt without dwelling on the result—whether you stumble or triumph holds no significance in the realm of learning.</p>
</blockquote>
<p>But how did I learn this?</p>
<p>Our C programming teacher was guiding us through the intricacies of coding when she posed an intriguing challenge: she wanted a student to jot down a program on the board. Understandably, the room was tinged with nervous excitement; this marked our maiden voyage into the realm of coding. However, I chose to embrace the moment, summoning my courage and raising my hand. With a determined spirit, I penned the program onto the board. Much to my astonishment, its execution unfolded flawlessly. This marked a turning point, a juncture where I resolved to always confront challenges head-on and derive wisdom from them. It's true, I encountered numerous failures along the way, but one constant remained—the unwavering journey of learning.</p>
<p>The second lesson that became apparent to me was when I began to realize that I could effortlessly formulate program logic, no matter how complex, all thanks to my solid grasp of technical fundamentals. Hence the second lesson 👇</p>
<blockquote>
<p>Strengthen your technical foundation; every challenge appears conquerable with a solid base.</p>
</blockquote>
<p>As I effortlessly grasped concepts, I started underestimating the necessity of rote memorization for exam answers. It took me a while to recognize that I was scoring lower than individuals who hadn't comprehended the concepts as deeply. Even when I elaborated extensively on the subject matter, a crucial element seemed to be lacking. It was at this point that I imbibed my third crucial lesson.</p>
<blockquote>
<p>Mastering concepts and their implementation is one thing, but translating that mastery into technical writing, enabling others to grasp your explanations, presents a whole different challenge.</p>
</blockquote>
<p>Understanding and mastering complex technical concepts is one facet of the journey, yet the challenge deepens when one strives to transform that mastery into written form, allowing others to seamlessly comprehend the explanations. I came to realize this disparity as I encountered difficulty in employing the precise technical language outlined in textbooks, unlike some of my peers who were doing it with repeated efforts put into memorizing the answers.</p>
<p>This discrepancy signalled the need for me to cultivate my writing skills, understanding that technical concepts cannot be communicated simplistically. The process of articulating these ideas in writing acts as a bridge between comprehension and effective communication. It is the path to finding clarity and depth, making sure the complexities of technical subjects are communicated accurately. This proficiency in technical writing extends beyond exam performance—it facilitates effective teaching, collaborative projects, and the seamless exchange of ideas in real-world scenarios.</p>
<p>Despite achieving a commendable score of 89.80%, fate dealt an unexpected hand as I found myself excluded from the initial allocation list of the degree college. This circumstance compelled me to accept whatever options were presented during the second and final round. The degree college I ended up in wasn't my initial preference. However, adhering to the philosophy that "everything happens for a reason," I chose to perceive this situation through that lens. But I will still say it was one of the best things that happened to me as,</p>
<blockquote>
<p>Sometimes you have to fall to bounce back even stronger.</p>
</blockquote>
<p>Having completed my diploma studies at a top-tier college in Maharashtra, the transition to a tier 3 college for my degree was undeniably challenging. Recognizing the hurdles that lay ahead, I embraced a strategic approach. In response, I made the conscious decision to become an active participant in coding clubs—incidentally, our college lacked one, but my friends and I rallied to establish it. This initiative facilitated engagement with individuals who shared my passion, fostering an environment in which I could thrive. By forming a circle of like-minded friends, I positioned myself for growth and development despite the demanding road that stretched ahead.</p>
<blockquote>
<p>Select your circle of friends thoughtfully, for they wield a substantial influence over your mindset.</p>
</blockquote>
<p>This journey transformed my thought processes and cognitive approaches significantly. Swiftly, I delved into a teaching internship, beginning to earn some dollars. It wasn't long before the realization dawned on me—I needed to undertake tangible real-world projects. Thus, I undertook the creation of a digital marketing website for my brother's business. This venture proved invaluable in enhancing my web development proficiency. As time progressed, fueled by three subsequent internships, I proudly adopted the title of a web developer. Moreover, amidst these endeavours, I dedicated time to learning about blockchain technology and attended web3 meetups to connect with like-minded and experienced individuals.</p>
<p>As I grew more adept at crafting projects across various programming languages, I learnt that once your foundational knowledge is solid, you can readily delve into the intricacies of any technology or language and make strides. Amidst my evolving interests, a key insight emerged—comprehending the significance of core fundamentals. Things like networking, databases, how programming works, operating systems, and hardware form the solid foundation for becoming skilled in different areas.</p>
<p>Over these 6 years, my journey led me through various domains - from DSA to Databases, then onto JavaScript and Android app development. Eventually, I found my niche in full-stack web development with a focus on blockchain technology.</p>
<p>That is when I learnt,</p>
<blockquote>
<p>Interests shift as new technologies emerge over time. The key to adapting smoothly is having a strong foundation in the basics of computer fundamentals.</p>
</blockquote>
<p>Embark on exploration and uncover what aligns with your passions. Avoid hastily narrowing your focus. Early specialization can limit your breadth of knowledge. Instead, venture across various domains, absorbing insights, until you discover the optimal fit that resonates most with you.</p>
<p>In this journey, hackathons stand as invaluable waypoints. They provide not only the chance to dabble in diverse fields but also to hone essential skills like quick adaptation, innovative thinking, and collaborating effectively under pressure. These experiences enrich your explorations, infusing your path with a potent blend of versatility and expertise, ultimately guiding you towards a destination where your passions and capabilities converge.</p>
<blockquote>
<p>Hackathons are where rapid thinking fuses with agile coding.</p>
</blockquote>
<p>Participating in hackathons provides a unique opportunity to boost your self-confidence in rapidly creating practical and impactful products within condensed timeframes and fast-paced environments. These intense events challenge you to harness your creativity, technical skills, and collaborative prowess to deliver solutions that address real-world problems. This immersive experience not only refines your technical abilities but also fosters adaptability, teamwork, and effective problem-solving. As a result, hackathons serve as a crucible where your development skills and personal growth converge, enriching your overall journey in tech.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>As I step forward into the ever-evolving landscape of technology, these lessons remain my North Star, guiding me through the challenges and opportunities that lie ahead. They remind me that the true essence of learning is not confined to textbooks and lectures; it's the fusion of experience, insight, and a relentless hunger to innovate.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Farcaster: Part 2;
Delta Graphs, Sync and Secure Messaging]]></title><description><![CDATA[In Part 1 of the Farcaster series, we delved into the intriguing mechanisms behind identity generation and authentication on this innovative social media protocol. Now, in Part 2, we are set to unveil the heart of Farcaster's operations - the Delta G...]]></description><link>https://blog.aditipolkam.me/understanding-farcaster-part-2-delta-graphs-sync-and-secure-messaging</link><guid isPermaLink="true">https://blog.aditipolkam.me/understanding-farcaster-part-2-delta-graphs-sync-and-secure-messaging</guid><category><![CDATA[social media]]></category><category><![CDATA[decentralization]]></category><category><![CDATA[farcaster]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sun, 13 Aug 2023 02:03:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690538880267/cf712a3f-07e7-4e08-9ac9-d240b81b8952.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In <a target="_blank" href="https://aditipolkam.hashnode.dev/understanding-farcaster-part-1-identity-generation-and-authentication">Part 1</a> of the Farcaster series, we delved into the intriguing mechanisms behind identity generation and authentication on this innovative social media protocol. Now, in Part 2, we are set to unveil the heart of Farcaster's operations - the Delta Graphs, Hub Sync Process, and Secure Messaging. These elements form the backbone of the platform, enabling seamless communication and collaboration among users while prioritizing privacy and data integrity.</p>
<h3 id="heading-delta-graphs-and-hubs">Delta Graphs and Hubs</h3>
<p>At the core of Farcaster's functionality lies the concept of "Delta Graphs." These graphs are dynamic structures that capture and represent the interactions between users in a flexible and efficient manner. These graphs find their home within hubs, which play a vital role as repositories for all user-generated content and information. As the size of a hub increases, so does the cost to run it efficiently, prompting the platform to introduce storage limits for users. Farcaster employs delta pruning to manage the vast amount of data generated over time. Older messages are archived to keep the platform efficient and clutter-free. However, Farcaster ensures that no user's storage is ever depleted by setting these limits judiciously. For those seeking additional storage beyond the allocated limits, Farcaster offers the option to pay for extra storage, accommodating users with diverse needs and preferences.</p>
<p>Farcaster's underlying architecture relies on hubs, which are collections of deltas. To ensure the smooth functioning of the platform, incentives are offered to companies building their apps and simpler API services. This encourages more hubs to operate, leading to a robust network.</p>
<p><strong>Delta Types</strong></p>
<ol>
<li>Casts: Public Broadcasting of Text</li>
</ol>
<p>Casts are the backbone of Farcaster, allowing users to share text publicly visible to all. Whether it's expressing thoughts, sharing updates, or making announcements, users can communicate with a broad audience through these public broadcasts.</p>
<ol>
<li>Reactions: Likes and Recasts</li>
</ol>
<p>Farcaster enables users to react to posts through likes and recasts (like shares or retweets). Liking a post indicates appreciation or agreement, while recasting allows users to amplify a message by sharing it with their followers.</p>
<ol>
<li>Amps: Endorsements of One User</li>
</ol>
<p>Amps provide a way for users to endorse another user on Farcaster. It serves as a virtual pat on the back, acknowledging someone's contributions or accomplishments.</p>
<ol>
<li>Verifications: Proofs of Ownership and Link Wallets</li>
</ol>
<p>In a world where identity verification is crucial, Farcaster allows users to provide proof of ownership and link their wallets securely. This feature enhances authenticity and trust among users.</p>
<ol>
<li>User Data: Metadata (Bio, Profile, etc.)</li>
</ol>
<p>Farcaster enables users to customize their profiles by adding metadata like a bio, profile picture, and other relevant information, allowing them to express their individuality and interests.</p>
<ol>
<li>Signers: Signing Key-Pair Created Initially</li>
</ol>
<p>For added security, Farcaster uses signing key pairs that are generated during the initial setup. These signers play a vital role in ensuring the authenticity and integrity of messages on the platform.</p>
<h3 id="heading-hub-sync">Hub Sync</h3>
<p>In the vast expanse of the digital landscape, we need a way for messages to propagate quickly and in a reliable way through the network, and Farcaster operates through interconnected hubs. These hubs play a crucial role in facilitating seamless communication between users, ensuring information reaches its intended recipients promptly.</p>
<p>Each hub knows the address of each other hub on the network. Gossip channels are set up between these hubs through which the communication is carried out. Whenever a new Hub is added, it must know the address of at least one hub to download the entire state of the network. Gossip protocol doesn’t guarantee the ordering of messages and some messages might be discarded by other hubs while downloading the data, so these hubs perform an out-of-band sync process to periodically request full state of the hub and update themselves likewise.</p>
<p>To resolve conflicts arising from different social graphs, hubs employ a "merge" function, which determines the true social graph. Rules within each hub dictate how conflicts are resolved, considering timestamps and hashes to make informed decisions.</p>
<h3 id="heading-secure-messaging-enabling-private-communication-through-advanced-encryption">Secure Messaging: Enabling Private Communication through Advanced Encryption</h3>
<p>Farcaster takes a proactive approach to safeguard sensitive information through a robust encryption process. This encryption methodology involves a combination of public-private key pairs, Key Defining Functions (KDFs), and advanced cryptographic techniques.</p>
<p>At the core of Farcaster's security model is the utilization of public-private key pairs. Both the sender and the receiver possess their unique set of keys – a public key and a private key. These keys serve a dual purpose: the public key is openly shared and used for encryption, while the private key remains confidential and is only accessible to the key owner. This asymmetric encryption ensures that only the intended recipient, who possesses the corresponding private key, can decrypt the messages encrypted with their public key.</p>
<p>To establish a shared secret between the sender and receiver, Farcaster employs a Key Defining Function (KDF). This function takes both the sender's private key and the recipient's public key as input and generates a secure shared secret key. The shared secret acts as the foundation for subsequent cryptographic processes, ensuring that any unauthorized party cannot access the key even if they intercept the communication.</p>
<p>From this shared secret, Farcaster generates two additional keys: KDF-key2 and a messaging key (MKey). The KDF2 key is derived using a secondary Key Defining Function, enhancing the complexity and strength of the encryption scheme. This multi-layered approach further fortifies the security of the communication channel.</p>
<p>However, the real strength of Farcaster's secure messaging lies in the messaging key (MKey). This key is crafted from the shared secret and is specifically designed to encrypt and decrypt the messages exchanged between the sender and receiver. As a result, every message is uniquely encrypted with the MKey, ensuring that even if an attacker were to gain access to one message, they would not be able to decrypt other messages without the MKey.</p>
<p>When a user sends a message through Farcaster, the platform employs the MKey to encrypt the content of the message before transmission. The recipient, in possession of their private key and the corresponding shared secret, can then decrypt the message using the MKey. This process ensures end-to-end encryption, where the message remains confidential throughout its journey and can only be read by the intended recipient.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Farcaster is a pioneering social media platform that goes beyond the conventional like-comment-share paradigm. By providing users with an array of delta types, secure messaging, and efficient data management, Farcaster empowers individuals to connect, collaborate, and share their thoughts and ideas in a secure and privacy-conscious environment. As social media continues to shape the way we communicate, Farcaster sets a new standard for inclusive, secure, and user-centric networking experiences.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Farcaster: Part 1; 
Identity Generation and Authentication]]></title><description><![CDATA[In the digital age, social media has become an integral part of our lives, transforming the way we interact, share, and perceive the world around us. However, the traditional landscape of social media has its fair share of challenges, including data ...]]></description><link>https://blog.aditipolkam.me/understanding-farcaster-part-1-identity-generation-and-authentication</link><guid isPermaLink="true">https://blog.aditipolkam.me/understanding-farcaster-part-1-identity-generation-and-authentication</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[social media]]></category><category><![CDATA[decentralization]]></category><category><![CDATA[Decentralised Identity]]></category><category><![CDATA[farcaster]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sun, 23 Jul 2023 11:54:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1690111800589/afba5d05-7630-4f6f-86c7-41c695b1e88c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the digital age, social media has become an integral part of our lives, transforming the way we interact, share, and perceive the world around us. However, the traditional landscape of social media has its fair share of challenges, including data privacy concerns, content manipulation, and the dominance of a few centralized platforms. But what if there was a way to revolutionize this system? Enter decentralized social media – a groundbreaking concept that has the power to reshape how we handle social identity and content across multiple platforms.</p>
<p>The decentralized approach to social media promises to foster an unprecedented level of transparency, privacy, and autonomy for users, heralding a new era of digital interaction. While decentralized social media holds great promise, it also comes with its fair share of challenges.</p>
<ol>
<li><p>Identity Verification Across Platforms</p>
</li>
<li><p>Authentication of Messages</p>
</li>
<li><p>Content Availability Across Platforms</p>
</li>
<li><p>Consistency in Rules and Moderation</p>
</li>
</ol>
<h3 id="heading-creation-of-trustworthy-identities">Creation of trustworthy identities</h3>
<p>Remembering a long and complex wallet address can indeed be quite challenging for users in the realm of decentralized finance and blockchain-based platforms. As we seek more user-friendly solutions, the idea of adopting a naming system akin to domain names and IP addresses holds considerable promise. However, we must tread carefully, as this approach presents a unique challenge - the possibility of identity squatting and impersonation.</p>
<p>Users could have a personalized and easy-to-remember username, like @yourname, associated with their wallet address. This would undoubtedly enhance the overall user experience, promoting broader adoption of decentralized applications and platforms. Yet, the catch lies in ensuring the security and authenticity of these usernames. In a decentralized system, there's no central authority governing username allocation, making it susceptible to identity theft and malicious actors. Imagine a scenario where someone manages to secure a coveted username like @twitter. They could potentially exploit this privileged position, masquerading as Twitter's official account and misleading users for malicious purposes. This could lead to scams, misinformation, and significant reputational damage to legitimate entities.</p>
<h3 id="heading-how-does-farcaster-come-into-the-picture">How does Farcaster come into the picture?</h3>
<p>By leveraging blockchain technology, Farcaster introduces a secure and privacy-centric approach, empowering users with full control over their digital identities. Below are some of the key benefits Farcaster brings to the world of decentralized social identities:</p>
<ol>
<li><p>Self-Sovereign Identities owned and controlled by users.</p>
</li>
<li><p>Unique Farcaster ID (FID) upon registration for ensuring seamless interactions across various decentralized applications without the need for repetitive account creation.</p>
</li>
<li><p>Human-Readable Farcaster Name (Fname) associated with FID simplifies the process of identification and enhances user experience.</p>
</li>
<li><p>Enhanced Security with Signers eliminating the need for users to expose their custody address's private key.</p>
</li>
<li><p>Account Recovery by setting up a designated recovery address to regain control of the accounts in case of compromise or loss of access.</p>
</li>
<li><p>Farcaster promotes interoperability among decentralized applications, enabling users to seamlessly navigate various platforms with a single set of credentials and data availability amongst various platforms.</p>
</li>
</ol>
<h3 id="heading-farcaster-identities">Farcaster Identities</h3>
<p>Farcaster maintains a dual identification system comprising a primary identifier known as the Farcaster ID (FID) and a secondary identifier known as the Farcaster Name (FName).</p>
<ol>
<li><p><strong>Farcaster ID (FID):</strong> The Farcaster ID issued by the ID Registry serves as the primary and fundamental identifier for users within the decentralized ecosystem. It is a cryptographically secure and globally unique identifier assigned to each user upon registration. The FID plays a critical role in facilitating secure transactions, interactions, and record-keeping on the Farcaster network. By using cryptographic techniques, the FID ensures that users can be identified and verified without relying on a central authority, maintaining the core principles of decentralization.</p>
</li>
<li><p><strong>Farcaster Name (FName):</strong> Recognizing the challenge of remembering long and complex FIDs, Farcaster introduces Farcaster Name (FName) as a user-friendly, human-readable alternative. This FName issued by the Name Registry allows users to create personalized and memorable names associated with their FIDs. For example, a user with FID "0x1a2b3c4d5e6f" could choose the FName "@username" for easier identification by other users on the platform. To ensure the integrity and security of the FName system, Farcaster employs a partially centralized service responsible for the allocation and management of FNames. This authority follows stringent protocols to prevent misuse, cyber-squatting, or impersonation. The allocation process is designed to be transparent, fair, and safeguarded against abuse, while also protecting the privacy of users' underlying FIDs.</p>
</li>
</ol>
<h3 id="heading-farcaster-authentication">Farcaster Authentication</h3>
<p>Authentication in web3 decentralized applications (dApps) operates on a fairly simple and secure premise. When using web3 dApps, the apps request users to sign messages using their private keys through their wallets. This process is fundamental to proving ownership and control over a specific blockchain address.</p>
<p>However, introducing third-party social media apps into the equation adds a layer of complexity and potential risk that users must be cautious about. These apps may request users to load their private keys into the application to facilitate the signing process. Doing so poses significant dangers, as sharing private keys with third-party services compromises the security of the user's funds and identity.</p>
<p>The Farcaster protocol introduces a novel approach to message signing by creating a separate signer public-private key pair. Now whenever the sender wants to send a message the social media app signs it using the signer already created. This innovative method enhances security and privacy by eliminating the need to use the sender's private key for signing messages. Consequently, the public address associated with the sender is now referred to as the "custody address."</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690100944204/3d693451-6693-4ed8-8949-4116cbab3b86.png" alt class="image--center mx-auto" /></p>
<p>When a user logs into any messaging app built on the Farcaster platform, two essential tasks are initiated to establish their identity and enable secure communication. Firstly, the app generates a unique Farcaster ID (FID) and Farcaster Name (Fname) for the user, utilizing the ID Registry and Name Registry on the Identity Layer. If the user does not already have an FID and Fname, this transaction creates them, ensuring a distinct and verifiable identity within the Farcaster network.</p>
<p>Subsequently, the app generates a new signer on the App Layer for the user. This signer serves as a cryptographic key pair, securely stored locally on the user's device. Its primary function is to sign messages on behalf of the user, providing a secure means of authentication without requiring the user's custody address's private key. Each application within the Farcaster ecosystem generates its own unique signer for the user, maintaining isolation and security between different applications.</p>
<p>Once the messages are signed by the user's signer, they are transmitted to the Farcaster hubs, which operate on the Data Layer of the Farcaster architecture. These hubs play a crucial role in syncing and maintaining a global state of the messages sent and received across the Farcaster network.</p>
<h3 id="heading-account-recovery-with-farcaster"><strong>Account Recovery with Farcaster</strong></h3>
<p>In Farcaster, users have the option to enhance the security of their accounts through the implementation of a recovery address. This recovery address acts as a fail-safe mechanism in case the user's primary custody address is compromised or inaccessible. When a user's account is compromised, the recovery address owner can initiate a transfer of ownership request to reclaim control of the account. However, to prevent any potential malicious actions, Farcaster enforces a 7-day waiting period before the transfer of ownership is completed. This grace period ensures that the request is genuine and not an attempt by unauthorized entities to take control of the account. By introducing this recovery address feature and the waiting period, Farcaster strikes a balance between robust security measures and user-friendly account recovery, safeguarding users' digital assets in the decentralized ecosystem.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>Farcaster's approach to authentication and identity generation represents a pioneering stride towards enhancing security, privacy, and user experience in the decentralized landscape. By introducing a separate signer public-private key pair, Farcaster eliminates the need for users to expose their custody address's private key during message signing, fortifying the protection of their digital assets.</p>
<p>The implementation of a recovery address further adds a layer of resilience to account security. Users can proactively set a designated recovery address, allowing them to reclaim control of their accounts in the event of compromise or access loss.</p>
<p>In a decentralized world where self-sovereignty is paramount, Farcaster's authentication and identity generation mechanisms set new standards for privacy and control over digital assets.</p>
]]></content:encoded></item><item><title><![CDATA[2022: A Year of Self-Reflection and Growth✨]]></title><description><![CDATA[As we step into 2023, it's time to look back at the past year and reflect on the amazing moments and experiences I've had. 2022 was a year of both challenges and triumphs, and a year that saw me grow and learn in ways I never thought were possible. F...]]></description><link>https://blog.aditipolkam.me/2022-year-review</link><guid isPermaLink="true">https://blog.aditipolkam.me/2022-year-review</guid><category><![CDATA[#DevRetro2022]]></category><category><![CDATA[Developer Blogging]]></category><category><![CDATA[developer-journey]]></category><category><![CDATA[yearinreview]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Sat, 31 Dec 2022 05:35:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672381476778/652dab94-831a-4d77-bb19-03d5f4dd2b12.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As we step into 2023, it's time to look back at the past year and reflect on the amazing moments and experiences I've had. 2022 was a year of both challenges and triumphs, and a year that saw me grow and learn in ways I never thought were possible. From the highs of incredible career achievements to the lows of difficult personal moments, the past year was a rollercoaster that tested my limits and taught me valuable lessons along the way. It's time to take a look back and celebrate the journey that was 2022!</p>
<h3 id="heading-january-2022">January 2022</h3>
<p>It's always exciting to start a new year and think about all the possibilities and opportunities it may bring. So started with a dedication to being a better developer and working on my physical health. Developed a personal project being more serious than ever before after a friend challenged me to do so. For the first time ever - no Youtube video references just pure use of API documentation of various libraries. Played handball for the first time and participated in the University games with just 2 days worth of practice. Guess what, I got selected for ZONALS.🤾‍♀️</p>
<p>Started learning about web3 and blockchain and YO, I liked it! LFG.</p>
<h3 id="heading-february-2022">February 2022</h3>
<p>Wanted some time off the screen so visited a bird sanctuary I had always wanted to visit. It is a very beautiful place and I enjoyed every single moment I spent there in the boat watching an entire regiment of FLAMINGOS and clicking so many breathtaking photos.</p>
<p><img src="https://lh3.googleusercontent.com/P9U0AGyj_mnk-OS36iV7KnyeiBo4YaPoZHCtvbICURQ8vl4-sO2adEPKl-p23j_mb9N-w5I_QLN_mUpgVH_vlGx_RRBoRoWrLpH01HEyrDOmyPxJtDP23vYUhFLuZch_qJwAkp3Ox1CCyr0tWp1EWr4VxgimBUhVhy3g1ppriu2aTe_7i1Qi1JXbQcAB9DdnQZo1EWOvQjgZCVHMxE-vuIPyWuYXc8T3LjB6Dy38oN6I_Oaqe7JemM8qCGmkxhP99OP5XpNUCKhUN1mxoU89-a8fuWOM5MNOXkMVGzyI7ksEQQ_BPP8Iz-sBdxe38prTxb4tuQlNH7e7kxXRG6AeQmorHdLanOhOpt4WRIgiXBZh-swRMxXf_Dke9iLGszmXdrmqBkUMWK9oEZSnbIUN2ED5Xj7AIhnNuMFtMJ-FcMdRpE0FUobeap3BPnCfxdw6cDTlXCw36hYKYenHvL9gh0g0epq_QCgHUk9wx8QaLlbooZA6S59DezVLxCbhpaG2BTs6HgASc35sOPMiCm94WG5du_rnDsdUHn7mb2Vg_tnszkw2hxs9HmqlQf2imVaXJ7nYLD3D4H4LinnhCarV7HTdXzBkGyYe1JW2MCcJPN_CzIHPtHkePwHFjUdLFK7HNvwmUX_Dk28VGyPa607CoSjsCko1BzgIvrwVBYJV-LoHkUrcg4zjR5K8Il9sVFhY-K4Z0-5auauw9XjPyyKv3REAEq-Ld1uK-Zg6Bqhl0Py6SmLJD_ADntRFIqOZ39EN4d4rZLts3TSz0RtknLWvnAmRtD9BepbFXxjH_MegNhDgLaYSNsqNVA8dmO_v_dmC-HmRAxRpkgCX1svg8xQ45xdCbw9z1FR-y-kESB0snZLPmNrrIVPxTvpOGE2GRRUHVPX1BV0OtZDAyhT2GbvOpN3zr9GOnOJ5M6i9KaNvAfsJiYw4CmRNL4JIt61HjrMTR4KfDPoBzkue_Ll7UZ33VvDGLKd65iaeBEQ0x56mIqWh1C48kFdfRQ=w1264-h948-no?authuser=0" alt /></p>
<p>Later continued my journey in learning web3 and blockchain basics along with developing some stuff. Met and bonded with a few friends from previous college whilst the small convocation was arranged and had a blast.</p>
<p>February was a calm and light month, basically. But yes I started competitive coding and was quite active on <a target="_blank" href="https://www.codechef.com/">Codechef</a> - a really good platform to practice coding for beginners and even pros. My friend and I use to take part in weekly challenges to improve our skills.</p>
<p>Bought a new domain for <a target="_blank" href="https://aditipolkam.me">my portfolio</a> too. LOL! 🚀</p>
<h3 id="heading-march-2022">March 2022</h3>
<p>March was literally a turning point in my life, experienced a small but very transformative heartbreak that changed my thought process. Decided to code like never before and then was introduced to some cool platforms to learn and build blockchain projects like <a target="_blank" href="https://www.learnweb3.io/">LearnWeb3</a> and <a target="_blank" href="https://buildspace.so/">Buildspace</a>. Got into a bit of frontend development for the projects I had to develop on these platforms and left my fear of frontend far behind. This time my friends and I decided to have a quick trip and we enjoyed River Rafting at Kolad, OH what a breathtaking experience it was!😍</p>
<p>Meanwhile learning web3 and competitive coding continues.</p>
<h3 id="heading-april-2022">April 2022</h3>
<p>April was a month full of dilemmas and gave me the clarity I needed in life. Overcame stage fright by opting to dance for a college event in front of 100+ people.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1513508192700952580">https://twitter.com/aditipolkam/status/1513508192700952580</a></div>
<p> </p>
<p>Visited Hyderabad after years and loved it this time. Finally, my hometown made me realize my mistakes and I corrected them this month after returning. Finally understood the meaning of the following quote,</p>
<blockquote>
<p>In search of gold, don't lose a diamond! 💎</p>
</blockquote>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1518405051923853312">https://twitter.com/aditipolkam/status/1518405051923853312</a></div>
<p> </p>
<p>Decided to keep things simple and not pressurize myself with everything that I want at a single time and started to work on things that really mattered to me.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1515999755733770252">https://twitter.com/aditipolkam/status/1515999755733770252</a></div>
<p> </p>
<p>Also, donated blood for the first time :)🩸</p>
<h3 id="heading-may-2022">May 2022</h3>
<p>May was beautiful and jolly but in the meantime, it was also resourceful. I had been hearing all the buzz about web3 meetups and stuff so finally decided to attend one. I was so afraid to go alone that I dragged a friend with me there. But yeah! It was a cool networking session and made some really great friends there. Met <a target="_blank" href="https://twitter.com/tamarincrypto">Tamar</a> from the Solana ecosystem there and I was really very inspired by her.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/tamarincrypto/status/1530584715530424320">https://twitter.com/tamarincrypto/status/1530584715530424320</a></div>
<p> </p>
<p>Worked on a Bill Spilting application with a completely new frontend framework this time. Building this one overjoyed me and boosted my self-confidence. My friends circle literally used this one to split bills amongst us. 🏆</p>
<p>Oh did I forget to mention? I even experienced a bike accident this month. Yes, my bike slipped over the water. GG!</p>
<h3 id="heading-june-2022">June 2022</h3>
<p>As the month of June approached, I knew that it would bring with it a host of new challenges and opportunities. One of the biggest challenges I faced was deciding how to spend my time and energy. There were so many different things I could be doing, and I wanted to make sure that I was making the most of every day.</p>
<p>One opportunity that presented itself was the chance to help a friend market the new app he had been working on at his startup, <a target="_blank" href="https://www.instagram.com/fosterreadsofficial/?hl=en">Foster Reads</a>. 📚</p>
<p>I spent time working closely with the entire team, helping to create promotional materials and coming up with a marketing strategy for the event. It was a lot of work, but it was also extremely rewarding.</p>
<p>And here was the time for another web3 meetup, this time had a little less anxiety and met some cool builders there. We talked about blockchains, some project ideas, and other technologies.</p>
<h3 id="heading-july-2022">July 2022</h3>
<p>Bruh, my birthday month🎂, and for the first time in my life the exam month too. Anyway passed with a pointer of 9.43 and had a cute birthday date. Later this month worked on my first frontend freelance gig and delivered a good working prototype to the client. Improved my frontend skills 100x times. July was so worked up that I needed a break and so visited Lohgad at peak monsoon times. The weather was soothing and the trek was refreshing.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1550678198626779138">https://twitter.com/aditipolkam/status/1550678198626779138</a></div>
<p> </p>
<h3 id="heading-august-2022">August 2022</h3>
<p>In the never-ending search for internships, I finally landed one this month. Took up a frontend role at <a target="_blank" href="https://cftlabs.org/">CFT Labs</a>.🖥 Tried my hands on Solana too :P Attended my first web3 event away from the city and of course, it had to be Web3Conf Goa. I can sit all day and write about how difficult it was to reach Goa with all the roads blocked due to heavy rainfall. Thank God we reached safe, and then the event gave me a whole new experience of the tech industry. Networking sessions OP!</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1558562850376822784">https://twitter.com/aditipolkam/status/1558562850376822784</a></div>
<p> </p>
<p>Returned to Pune with loads of memories only to realize I had lots of pending work from my new internship. I struggled to understand the code written by someone else and took too much time to settle in. Fell sick thrice with the pressure of work and realized I had to cope. After a few days, I started to work with more dedication and finally was at mental peace.</p>
<h3 id="heading-september-2022">September 2022</h3>
<p>Strived for the entire month working on the internship project, and learned so many new things about frontend development. Improved my problem-solving approach, error handling, and dynamic screen updations.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1570684992443023361">https://twitter.com/aditipolkam/status/1570684992443023361</a></div>
<p> </p>
<p>This month I wrote my first piece of article on a web3 project and researched the technical side of that project. It was finally time to say goodbye as I wanted something related to the blockchain field and later this month joined <a target="_blank" href="https://www.wowlabz.com/">WowLabz</a> as a technical writer for web3 and metaverse.✍</p>
<p>Meanwhile, I was continuing coding and learning Solidity too.</p>
<h3 id="heading-october-2022">October 2022</h3>
<p>October was a busy and exciting month for me, as I was given the opportunity to become the <a target="_blank" href="https://twitter.com/tpg_pune">TPG Pune</a> chapter lead. <a target="_blank" href="https://twitter.com/PhoenixGuildHQ">The Phoenix Guild</a>, or TPG, is a non-profit organization that is dedicated to fostering education and diversity in the web3 community. ☀</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1581981155343360001">https://twitter.com/aditipolkam/status/1581981155343360001</a></div>
<p> </p>
<p>As the TPG Pune chapter lead, I was responsible for organizing and leading events and initiatives in my local community. This was a big responsibility, but I was excited about the opportunity to make a difference in my community and help promote the values of the TPG.</p>
<p>I also started learning advanced Solidity from the TPG Solidity Bootcamp and it was really helpful for me to understand concepts in detail.</p>
<h3 id="heading-november-2022">November 2022</h3>
<p>November was a month full of firsts for me. One of the biggest achievements of the month was writing my very first blog on the <a target="_blank" href="https://aditipolkam.hashnode.dev/erc20-token-standard">ERC20 token standard</a> and publishing it on Hashnode. This was a topic that I had been interested in for a while.</p>
<p>I also conducted my first workshop for <a target="_blank" href="https://shardeum.org/">Shardeum</a>, a Layer 1 blockchain company. The workshop was focused on introducing participants to the basics of smart contracts and deploying custom tokens, and I was thrilled to be able to share my knowledge with a new audience.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/RamprasadVV/status/1591402930858430465">https://twitter.com/RamprasadVV/status/1591402930858430465</a></div>
<p> </p>
<p>In addition to these achievements, I was also accepted to participate in EthIndia, a web3 hackathon in Bangalore. This was a huge honor, as the hackathon is one of the most prestigious in the web3 community.</p>
<p>To top it all off, November was also the month that I took my very first flight. ✈ I was nervous but excited to embark on this new adventure, and I was looking forward to meeting new people and learning new things at the hackathon.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1597194254363025408">https://twitter.com/aditipolkam/status/1597194254363025408</a></div>
<p> </p>
<p>Overall, November was a month of growth and opportunity for me, and I was grateful for all of the experiences and challenges that it brought my way.</p>
<h3 id="heading-december-2022">December 2022</h3>
<p>Participating in EthIndia and the TPG Hacker House was an incredible experience for me. From the moment I arrived in Bangalore, I knew that this was going to be a special trip. I had the opportunity to speak at the dAOs 3.0 event in Bangalore.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/rep3gg/status/1597208658567663618">https://twitter.com/rep3gg/status/1597208658567663618</a></div>
<p> </p>
<p>The hackathon itself was an intense and exciting event, and I loved being surrounded by so many talented and passionate people. I was a little nervous at first, as I wasn't sure how well I would be able to keep up with the other participants. Unfortunately, things didn't go exactly as planned for our team. We struggled with project ideation and ended up having to pivot to a new idea at the last minute. It was a bit of a mess, but we were determined to make the most of the opportunity. In the end, we managed to pull together a quick project that got us through the hackathon. It wasn't our best work, but we were proud of what we had accomplished given the circumstances.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/aditipolkam/status/1600074893911265281">https://twitter.com/aditipolkam/status/1600074893911265281</a></div>
<p> </p>
<p>After returning to Pune from EthIndia, I was feeling energized and motivated to continue working on my skills. I had learned so much at the hackathon and had made some great connections, and I was determined to make the most of these opportunities.</p>
<p>One way that I decided to do this was by participating in a virtual hackathon. This was a new experience for me, as I had never participated in a virtual hackathon before. But I was excited for the chance to test my skills and see what I was capable of. I decided to go solo for this hackathon, which was a bit of a risk. But I was confident in my abilities and wanted to prove to myself that I could succeed as a solo hacker. The hackathon was a lot of work, but it was also a lot of fun. I enjoyed the challenge of working on a project completely on my own, and I was proud of the end result. In the end, I was able to submit a project that I was really proud of, and I felt great about my progress.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=VA6Ny--lCrI">https://www.youtube.com/watch?v=VA6Ny--lCrI</a></div>
<p> </p>
<p>The end of December was a cherry on top of an already exciting year for me. After months of hard work and dedication, I finally got a college placement offer as a developer at a highly sought-after software company. To top it off, I was also selected to be a member of the <a target="_blank" href="https://twitter.com/developer_dao">Developer DAO</a>.✨</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/wslyvh/status/1608885045691035654">https://twitter.com/wslyvh/status/1608885045691035654</a></div>
<p> </p>
<h3 id="heading-quick-recap">Quick recap</h3>
<p>This entire year has been full of ups and downs, with moments of joy and sorrow, success and failure, having lots of fun to completely losing my mind. Despite the challenges, I have remained determined and motivated to keep pushing forward.</p>
<p>There have been times when things seemed impossible, and I wasn't sure if I would be able to overcome the obstacles in front of me. But I have always found the strength and resilience to keep going, and I am proud of everything that I have accomplished this year.</p>
<p>I have learned so much and grown in so many ways, and I am grateful for all of the experiences and challenges that have come my way. By sharing my experiences, I hope to provide insight and inspiration to others who may be going through similar experiences and to read amazing experiences by other developers you can check out posts for <strong><em>Dev Retro 2022</em></strong> from <strong><em>Hashnode.</em></strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672386614181/a7eb1299-6d10-48e0-b596-7d4d9aa3e53c.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-2023-i-am-waiting">2023, I am waiting ....</h3>
<p>Looking ahead to 2023, I have the energy and enthusiasm to make it an even more amazing year. I am excited about the opportunity to continue learning and growing, and I am ready to take on whatever challenges come my way.</p>
<p>No matter what the future holds, I know that I am up to the task, and I am confident that I will be able to make the most of every opportunity that comes my way. 🤝</p>
]]></content:encoded></item><item><title><![CDATA[Importance of managing blockchain information and how does Covalent API help the same?]]></title><description><![CDATA[Have you ever been curious about how data that is stored on a blockchain can be accessed? Blockchain is a revolutionary technology that allows for secure data storage, and understanding how to access this data can be a difficult concept to grasp. Man...]]></description><link>https://blog.aditipolkam.me/get-started-with-covalent-api</link><guid isPermaLink="true">https://blog.aditipolkam.me/get-started-with-covalent-api</guid><category><![CDATA[covalent api]]></category><category><![CDATA[blockchain data]]></category><category><![CDATA[indexing]]></category><category><![CDATA[Blockchain]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Wed, 07 Dec 2022 07:34:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670394362732/j6guJ2_rI.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever been curious about how data that is stored on a blockchain can be accessed? Blockchain is a revolutionary technology that allows for secure data storage, and understanding how to access this data can be a difficult concept to grasp. Managing blockchain information can be a difficult task, due to the complexity of the technology. Blockchain is a distributed ledger technology that enables secure and transparent information storage and is used to create a digital chain of information that can be shared among multiple parties. The challenge of managing blockchain information lies in the fact that the data is stored on a decentralized network, making it difficult to access and update. In addition, the data stored on the blockchain is immutable, meaning that it cannot be changed or deleted. This can make it difficult to update or delete information, as any changes need to be done through the consensus of the network participants. Finally, the complexity of the technology can make it difficult to understand and use. This can lead to errors and mistakes, which can have serious repercussions. Overall, managing blockchain information can be a difficult task due to the complexity of the technology, the difficulty of accessing and updating the data, and the immutability of the data stored on the blockchain. </p>
<h3 id="heading-accessing-data-on-the-blockchain">Accessing data on the blockchain</h3>
<p>Blockchain information needs to be indexed and made accessible in order to increase transparency, security, and trust in the data stored on the blockchain. By making this data accessible, users can more easily verify the accuracy of the information, ensure the security of their data and trace the source of the data. Additionally, by indexing the data, users can quickly and efficiently search the blockchain for specific information, such as transactions, contracts, and ownership records. This will make it easier for users to audit and analyze the data stored on the blockchain, as well as to identify any potential security vulnerabilities. Furthermore, indexing and making blockchain data accessible will enable developers to create powerful applications that utilize the data in a secure, transparent, and efficient way. Therefore, it is essential that blockchain information is indexed and made accessible in order to ensure the integrity and security of the data stored on the blockchain.
But how do we do it, technically?</p>
<h3 id="heading-enter-covalent">Enter Covalent.</h3>
<p>Covalent is a unified API that helps to organize the world's blockchain information, providing users with an easy-to-use interface and a comprehensive set of tools. It is the only multi-chain API that provides access to deep, granular, and historical blockchain data. Covalent has indexed the entire blockchain so nothing really remains inaccessible. Covalent API’s features help to make sense of the vast amounts of data that are generated from the various blockchains. It enables users to track, analyze, and visualize the data from multiple networks and blockchains, providing users with a comprehensive view of their data. Covalent’s tools are designed to make it easier for users to understand the data from different networks. It provides interactive visualizations of the data, allowing users to quickly spot trends and identify anomalies. It also provides powerful analytics tools that allow users to gain deeper insights into the data. In addition, Covalent provides users with access to a wide range of APIs, allowing them to easily access and integrate data from different networks. This makes it easier to build applications that need to access data from multiple blockchains. Overall, Covalent is a powerful platform that helps to make sense of the data generated by the world’s blockchains. It provides users with an easy-to-use interface and a comprehensive set of tools that make it easier to understand and analyze the data.
Covalent Query Token (CQT) is a proof of stake (PoS) governance token powering the Covalent network.</p>
<h3 id="heading-using-the-covalent-unified-api">Using the Covalent Unified API</h3>
<p>You can access the API <a target="_blank" href="https://www.covalenthq.com/docs/api/#/0/0/USD/1">here</a> on the <a target="_blank" href="https://www.covalenthq.com/">official website</a>.</p>
<h4 id="heading-you-need-an-api-key-to-get-started-with-the-api-which-you-can-generate-by-creating-your-account-click-on-get-an-api-key">You need an API key to get started with the API which you can generate by creating your account - click on 'Get an API key'</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1670401667811/-0pWDh-9Y.png" alt="image.png" /></p>
<h4 id="heading-example-to-get-transactions-for-address-using-covalent-api">Example: To get transactions for address using Covalent API</h4>
<p>request format: <code>https://api.covalenthq.com/v1/{chain_id}/address/{wallet_address}/transactions_v2/</code></p>
<p>According to the docs, this returns all transactions along with their decoded log events. This endpoint does a deep crawl of the blockchain to retrieve all kinds of transactions that reference the address including indexed topics within the event logs given chain_id and wallet_address</p>
<p>so a sample request on the 'Polygon Mumbai Testnet' would look like: <code>https://api.covalenthq.com/v1/80001/address/0xE5C73643Fba5652635207c689091A00eeAdae644/transactions_v2/</code></p>
<p>returning data in a JSON object like this, with <code>items</code> array having details of every transaction on that address</p>
<pre><code>{
   <span class="hljs-string">"address"</span>: <span class="hljs-string">"0xe5c73643fba5652635207c689091a00eeadae644"</span>,
   <span class="hljs-string">"updated_at"</span>: <span class="hljs-string">"2022-12-07T07:00:28.983983340Z"</span>,
   <span class="hljs-string">"next_update_at"</span>: <span class="hljs-string">"2022-12-07T07:05:28.983983720Z"</span>,
   <span class="hljs-string">"quote_currency"</span>: <span class="hljs-string">"USD"</span>,
   <span class="hljs-string">"chain_id"</span>: <span class="hljs-number">80001</span>,
   <span class="hljs-string">"items"</span>: []
}
</code></pre><h3 id="heading-other-significant-api-requests">Other significant API requests</h3>
<h4 id="heading-1-get-historical-portfolio-value-over-time">1. Get historical portfolio value over time</h4>
<p>returns wallet value for the last 30 days at 24 hour interval timestamps.</p>
<h4 id="heading-2-get-erc20-token-transfers-for-address">2. Get ERC20 token transfers for address</h4>
<p>returns all ERC20 token contract transfers along with their historical prices at the time of their transfer.</p>
<h4 id="heading-3-get-nft-transactions-for-contract">3. Get NFT transactions for contract</h4>
<p>returns a list of transactions for the particular contract.</p>
<h3 id="heading-final-thoughts">Final Thoughts</h3>
<p>In conclusion, the Covalent unified API offers a powerful and convenient solution for indexing blockchain data. With its robust and easy-to-use interface, it allows users to quickly and easily access the information they need from multiple blockchain networks. This makes it an invaluable tool for developers and other users who need to work with blockchain data on a regular basis. Its ability to provide a unified view of data from multiple blockchains is particularly useful, as it allows users to easily compare and analyze data from different networks in a single platform. Overall, the API is a valuable resource for anyone looking to index and work with blockchain data.</p>
]]></content:encoded></item><item><title><![CDATA[Everything you need to know about the ERC20 token standard]]></title><description><![CDATA[What is a token?
A token is a type of digital asset that can be used for numerous purposes like tickets to social events, payment systems, etc. They can basically represent anything and everything. Tokens may be used as proof of ownership for digital...]]></description><link>https://blog.aditipolkam.me/erc20-token-standard</link><guid isPermaLink="true">https://blog.aditipolkam.me/erc20-token-standard</guid><category><![CDATA[erc20 explained]]></category><category><![CDATA[ERC20]]></category><category><![CDATA[ERC20tokendevelopment]]></category><category><![CDATA[token]]></category><category><![CDATA[Ethereum]]></category><dc:creator><![CDATA[Aditi Polkam]]></dc:creator><pubDate>Wed, 23 Nov 2022 12:09:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1669191576893/1JnuvS3Ta.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-a-token">What is a token?</h2>
<p>A token is a type of digital asset that can be used for numerous purposes like tickets to social events, payment systems, etc. They can basically represent anything and everything. Tokens may be used as proof of ownership for digital collectibles or even physical world items. They are also used to raise funds from the community.</p>
<blockquote>
<p>Tokens are to crypto, what shares are to the stock market💸</p>
</blockquote>
<p>Tokens are cryptocurrencies that are built on top of another blockchain (they are not native assets of the blockchain like ETH is to Ethereum and SOL is to Solana)</p>
<p>While every blockchain follows different rules and regulations to create and manage tokens, ERC20 is a standard used by Ethereum-based blockchains to fulfill this purpose.</p>
<h2 id="heading-the-erc-20-standard">The ERC-20 standard</h2>
<p>ERC stands for Ethereum Request for Comment. The Ethereum-based tokens created using this standard are fungible tokens meaning that each token when replaced with another of its kind holds the same value in nature as the previous one. For example, if you replace a $1 note with another $1, it still values at $1. The same applies to cryptocurrencies like Bitcoin and Ethereum. (1 BTC will always be equal to 1 BTC)
In simple words, ERC-20 tokens are interchangeable.</p>
<p>A token contract should have these 5 basic functionalities:</p>
<ol>
<li><strong>Transfer</strong> - transfer tokens from one address to another</li>
<li><strong>Mint</strong>  - create new tokens to increase the supply</li>
<li><strong>Burn</strong>  - remove the tokens from supply (sending them to <code>address(0)</code>)</li>
<li><strong>Approve</strong> - allow an address to take control of owner's tokens</li>
<li><strong>Transferfrom</strong>  - transfer tokens from some address to another, only an address approved to do so by the owner of tokens can perform this operation</li>
</ol>
<p>Popularly, ERC-20 tokens are created using Openzeppelin's ERC-20 contract which can be found <a target="_blank" href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol">here</a>.</p>
<p>It takes only 5 lines of code to actually create ERC20 tokens but the logic behind the same is often unknown to many Solidity developers (which btw is a very big no-no).</p>
<p>So moving on to understanding the code of the ERC-20 contract which we inherit for our custom token contract. LFG.🚀</p>
<p>A contract binds together variables and functions. </p>
<h3 id="heading-state-variables-and-mappings">State variables and mappings:</h3>
<p>The statement <code>uint public _totalSupply;</code> indicates a variable name _totalSupply with data type uint(unsigned integer) is created to maintain a count of the total tokens that are created and are currently in supply</p>
<p><code>mapping(address =&gt; uint) public _balances;</code> maps address to a uint number which keeps a track of the total tokens a particular address holds</p>
<p><code>mapping(address =&gt; mapping(address =&gt; uint)) public _allowances;</code> is a nested mapping and is used to approve a particular address to spend some amount of tokens on behalf of the sender (delegate control)
here the first address is the one whose control of tokens is delegated to the second address. uint holds the number of tokens that a particular address is allowed to spend</p>
<p><code>string private _name;</code> stores the name of the token you will create like Aptos</p>
<p><code>string private _symbol;</code> stores the symbol for the token like APT</p>
<p>the constructor of the contract will assign these values - _name and _symbol</p>
<pre><code> <span class="hljs-keyword">constructor</span>(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }
</code></pre><h3 id="heading-functions">Functions</h3>
<p><strong>1.transfer</strong> </p>
<p>Function <code>transfer</code> is a virtual function that returns a boolean and takes two arguments</p>
<p>  a. to - the recipient to whom the tokens are to be transferred </p>
<p>  b. amount - how many tokens are to be transferred to the 
  recipient</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transfer</span>(<span class="hljs-params">address to, uint256 amount</span>) <span class="hljs-title">public</span> <span class="hljs-title">virtual</span> <span class="hljs-title">override</span> <span class="hljs-title">returns</span> (<span class="hljs-params">bool</span>) </span>{
        address owner = _msgSender();
        _transfer(owner, to, amount);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
</code></pre><p><code>transfer</code> function then calls another <strong>internal</strong> function <code>_transfer</code> (with an additional argument of <code>owner</code> that stores the sender address) which executes the main logic of transferring tokens from one address to another</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_transfer</span>(<span class="hljs-params">
        address from,
        address to,
        uint256 amount
    </span>) <span class="hljs-title">internal</span> <span class="hljs-title">virtual</span> </span>{
        <span class="hljs-built_in">require</span>(<span class="hljs-keyword">from</span> != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: transfer from the zero address"</span>);
        <span class="hljs-built_in">require</span>(to != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: transfer to the zero address"</span>);

        _beforeTokenTransfer(<span class="hljs-keyword">from</span>, to, amount);

        uint256 fromBalance = _balances[<span class="hljs-keyword">from</span>];
        <span class="hljs-built_in">require</span>(fromBalance &gt;= amount, <span class="hljs-string">"ERC20: transfer amount exceeds balance"</span>);
        unchecked {
            _balances[<span class="hljs-keyword">from</span>] = fromBalance - amount;
            <span class="hljs-comment">// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by</span>
            <span class="hljs-comment">// decrementing then incrementing.</span>
            _balances[to] += amount;
        }

        emit Transfer(<span class="hljs-keyword">from</span>, to, amount);

        _afterTokenTransfer(<span class="hljs-keyword">from</span>, to, amount);
    }
</code></pre><p>Here, it is checked if both addresses are valid with the <code>require</code> conditions
then an optional function <code>_beforeTokenTransfer(from, to, amount);</code> can be called if there are some steps to be executed before the token transfer</p>
<p><code>uint256 fromBalance = _balances[from];</code> gets the sender's balance from the mapping <code>_balances</code></p>
<p><code>require(fromBalance &gt;= amount, "ERC20: transfer amount exceeds balance");</code> is used to check if the sender has enough balance for the specified <code>amount</code> to be transferred
if the condition <code>fromBalance &gt;= amount</code> is not satisfied then the transaction reverts with message 'ERC20: transfer amount exceeds balance'</p>
<p>If everything goes well, we deduct the balance of sender and increase the balance of the receiver with 
<code>_balances[from] = fromBalance - amount;</code> &amp; <code>_balances[to] += amount;</code></p>
<p>Finally an event <code>emit Transfer(from, to, amount);</code> is emitted indicating successful transfer of function, and an optional function <code>_afterTokenTransfer(from, to, amount);</code> can be executed if required.</p>
<p><strong>2._mint</strong> </p>
<p>This function takes an address <code>account</code> to whom the tokens will be transferred after minting and <code>amount</code> i.e. the number of tokens to be minted</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_mint</span>(<span class="hljs-params">address account, uint256 amount</span>) <span class="hljs-title">internal</span> <span class="hljs-title">virtual</span> </span>{
        <span class="hljs-built_in">require</span>(account != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: mint to the zero address"</span>);

        _beforeTokenTransfer(address(<span class="hljs-number">0</span>), account, amount);

        _totalSupply += amount;
        unchecked {
            <span class="hljs-comment">// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.</span>
            _balances[account] += amount;
        }
        emit Transfer(address(<span class="hljs-number">0</span>), account, amount);

        _afterTokenTransfer(address(<span class="hljs-number">0</span>), account, amount);
    }
</code></pre><p>Here too, the address is checked to be a valid one before any other transaction is carried out.</p>
<p> <code>_totalSupply += amount;</code> increases the total supply of tokens by <code>amount</code></p>
<p><code>_balances[account] += amount;</code> increases the balance of the <code>account</code> whose address was given with the <code>_mint</code> function by the number of tokens minted and finally emits a <code>Transfer</code> event</p>
<p><strong>3._burn</strong></p>
<p>This function has almost the same steps as getting the balance of the account in the <code>_mint</code> function except, instead of creating new tokens it destroys the already created ones and removes them from circulation decreasing the total supply.</p>
<pre><code> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_burn</span>(<span class="hljs-params">address account, uint256 amount</span>) <span class="hljs-title">internal</span> <span class="hljs-title">virtual</span> </span>{
        <span class="hljs-built_in">require</span>(account != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: burn from the zero address"</span>);

        _beforeTokenTransfer(account, address(<span class="hljs-number">0</span>), amount);

        uint256 accountBalance = _balances[account];
        <span class="hljs-built_in">require</span>(accountBalance &gt;= amount, <span class="hljs-string">"ERC20: burn amount exceeds balance"</span>);
        unchecked {
            _balances[account] = accountBalance - amount;
            <span class="hljs-comment">// Overflow not possible: amount &lt;= accountBalance &lt;= totalSupply.</span>
            _totalSupply -= amount;
        }

        emit Transfer(account, address(<span class="hljs-number">0</span>), amount);

        _afterTokenTransfer(account, address(<span class="hljs-number">0</span>), amount);
    }
</code></pre><p><code>uint256 accountBalance = _balances[account];</code> get balance of account who is willing to destroy their tokens</p>
<p><code>require(accountBalance &gt;= amount, "ERC20: burn amount exceeds balance");</code> checks if there is enough balance</p>
<p><code>_balances[account] = accountBalance - amount;</code> subtracts the balance by the <code>amount</code> of tokens to be burnt and then reduces the total supply with <code>_totalSupply -= amount;</code></p>
<p>Finally, a <code>Transfer</code> event is emitted. Note that the account that receives the token is <code>address(0)</code> which means they are sent to an address that cannot be operated.</p>
<p><strong>4.approve</strong></p>
<p>This function approves a particular address <code>spender</code> to spend <code>amount</code> tokens on behalf of the <code>owner</code> - sender of this message</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">approve</span>(<span class="hljs-params">address spender, uint256 amount</span>) <span class="hljs-title">public</span> <span class="hljs-title">virtual</span> <span class="hljs-title">override</span> <span class="hljs-title">returns</span> (<span class="hljs-params">bool</span>) </span>{
        address owner = _msgSender();
        _approve(owner, spender, amount);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
</code></pre><p>It calls another internal function that is <code>_approve(owner, spender, amount);</code></p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_approve</span>(<span class="hljs-params">
        address owner,
        address spender,
        uint256 amount
    </span>) <span class="hljs-title">internal</span> <span class="hljs-title">virtual</span> </span>{
        <span class="hljs-built_in">require</span>(owner != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: approve from the zero address"</span>);
        <span class="hljs-built_in">require</span>(spender != address(<span class="hljs-number">0</span>), <span class="hljs-string">"ERC20: approve to the zero address"</span>);

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }
</code></pre><p>The changes are made in the <code>_allowances</code> mapping with <code>_allowances[owner][spender] = amount;</code> </p>
<p>This basically means 'approve the <code>spender</code> to spend <code>amount</code> number of tokens on behalf of the <code>owner</code>' and typically the mapping structure is somewhat like this
<strong>owner ---&gt; (spender ---&gt; amount)</strong></p>
<p>An event is emitted with <code>emit Approval(owner, spender, amount);</code> which indicates successful approval</p>
<p><strong>5.transferFrom</strong></p>
<p>This function has 3 arguments, 
from - owner address (owner may not be the message's sender)
to - receiver address
amount - number of tokens to be transferred</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transferFrom</span>(<span class="hljs-params">
        address from,
        address to,
        uint256 amount
    </span>) <span class="hljs-title">public</span> <span class="hljs-title">virtual</span> <span class="hljs-title">override</span> <span class="hljs-title">returns</span> (<span class="hljs-params">bool</span>) </span>{
        address spender = _msgSender();
        _spendAllowance(<span class="hljs-keyword">from</span>, spender, amount);
        _transfer(<span class="hljs-keyword">from</span>, to, amount);
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
</code></pre><p>It eventually calls another internal function <code>_spendAllowance(from, spender, amount);</code> which has the main logic to check how much amount of tokens can the approved addresses transfer</p>
<p><code>_transfer(from, to, amount);</code> uses the logic as explained above to transfer tokens from one address to another</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_spendAllowance</span>(<span class="hljs-params">
        address owner,
        address spender,
        uint256 amount
    </span>) <span class="hljs-title">internal</span> <span class="hljs-title">virtual</span> </span>{
        uint256 currentAllowance = allowance(owner, spender);
        <span class="hljs-keyword">if</span> (currentAllowance != type(uint256).max) {
            <span class="hljs-built_in">require</span>(currentAllowance &gt;= amount, <span class="hljs-string">"ERC20: insufficient allowance"</span>);
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }
</code></pre><p>function <code>allowance(owner, spender)</code> </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">allowance</span>(<span class="hljs-params">address owner, address spender</span>) <span class="hljs-title">public</span> <span class="hljs-title">view</span> <span class="hljs-title">virtual</span> <span class="hljs-title">override</span> <span class="hljs-title">returns</span> (<span class="hljs-params">uint256</span>) </span>{
        <span class="hljs-keyword">return</span> _allowances[owner][spender];
    }
</code></pre><p>calculates how many tokens owned by the <code>owner</code> are allowed to be controlled by the <code>spender</code> and assigns it to <code>currentAllowance</code></p>
<p>The<code>_spendAllowance</code> function then checks if <code>currentAllowance</code> that is the number of tokens approved to be controlled by the <code>spender</code> is greater than or equal to the <code>amount</code> of tokens to be transferred</p>
<p>Then <code>_approve(owner, spender, currentAllowance - amount)</code> is called to set the new approval limit and executes as explained above</p>
<p>Here new approval limit will be calculated by subtracting the tokens that will be transferred now(<code>amount</code>) from the total number of tokens allowed(<code>currentAllowance</code>)</p>
<p>After the <code>_spendAllowance</code> function in the <code>transferFrom</code> function is rightfully executed a call to <code>_transfer(from, to, amount);</code> is made which executes the transfer of tokens from one address to another.</p>
<h4 id="heading-additions">Additions</h4>
<p>The functions <code>increaseAllowance</code> and <code>decreaseAllowance</code> increase or decrease the number of tokens that can be controlled by the spender on behalf of the owner.</p>
<h3 id="heading-finally-let-us-write-a-contract-to-deploy-our-own-token-on-the-blockchain">Finally, let us write a contract to deploy our own token on the blockchain</h3>
<pre><code><span class="hljs-comment">//SPDX-License-Identifier: UNLICENSED</span>
pragma solidity ^<span class="hljs-number">0.8</span><span class="hljs-number">.0</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"</span>;

contract BlogToken is ERC20{
    <span class="hljs-keyword">constructor</span>(string memory _name, string memory _symbol) ERC20(_name, _symbol){
        _mint(msg.sender, <span class="hljs-number">10000</span> * <span class="hljs-number">10</span>**<span class="hljs-number">18</span>);
    }
}
</code></pre><p>Note: This is a small contract to show a demo of how our own 10000 tokens can be deployed to the blockchain using <code>_mint</code> and the contract to professionally deploy a token will have a lot more functionality like approve, transferFrom, and others.</p>
]]></content:encoded></item></channel></rss>