<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anirudh Makhana on Medium]]></title>
        <description><![CDATA[Stories by Anirudh Makhana on Medium]]></description>
        <link>https://medium.com/@anirudhmakhana?source=rss-c8296a5bbaec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kZs_ttDetzzEn5cA</url>
            <title>Stories by Anirudh Makhana on Medium</title>
            <link>https://medium.com/@anirudhmakhana?source=rss-c8296a5bbaec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:36:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anirudhmakhana/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[building relay infrastructure at scale: architecture and learnings]]></title>
            <link>https://medium.com/@anirudhmakhana/building-relay-infrastructure-at-scale-architecture-and-learnings-4e2eac27400f?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e2eac27400f</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 16:15:37 GMT</pubDate>
            <atom:updated>2026-04-24T16:15:37.181Z</atom:updated>
            <content:encoded><![CDATA[<p>what does it actually take to abstract gas away from users at scale? here’s the architecture behind it and what i learned building it.</p><h4>background</h4><p>this is a personal writeup documenting the architecture of a relay infrastructure system i worked on at a web3 infrastructure company. the goal is twofold: to document how the system was designed, and to capture what i learned about building backend software at scale. some implementation details are fuzzy or missing from memory, and i’ve noted those explicitly.</p><h3>what is relay?</h3><p>a relay is a meta-transaction infrastructure that allows developers to submit transactions on behalf of their users without users needing to hold native gas tokens. the system i worked on supported several transaction types:</p><ul><li>sponsoredCall and sponsoredCallERC2771: the sponsor (dapp developer) pays for gas via a prepaid gas tank. the ERC2771 variant adds support for msg.sender context via a trusted forwarder.</li><li>callWithSyncFee and callWithSyncFeeERC2771: the target contract itself pays the relay fee synchronously during execution. the relayer gets paid back inline.</li><li>bundler operations like eth_sendUserOperation: ERC-4337 account abstraction support, where the platform acted as a bundler.</li></ul><p>the system was built as a microservices architecture in nodejs/express, with services communicating over rabbitmq (inter-service) and bullmq/redis (intra-service). each service had a clear, narrow responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*KVKRuvRiypt6N8h1.jpg" /></figure><h3>services overview</h3><h4>1. api-gateway</h4><p>the entry point for all incoming requests. every relay call from an external developer first hit the api-gateway before being routed anywhere.</p><p>responsibilities:</p><ul><li>api key validation: every request needed a valid api key, validated at this layer before anything else happened</li><li>rate limiting: enforced per api key to prevent abuse</li><li>auth: broader authentication checks</li><li>routing: once a request was validated, the gateway routed it to the appropriate downstream service based on the method.</li></ul><p><strong>learning:</strong> putting cross-cutting concerns like auth, rate limiting, and routing in a single gateway layer is a clean pattern at scale. it means downstream services don’t each need to reimplement auth logic, and you have one place to enforce access control policy. this is the api gateway pattern, and it maps closely to what tools like aws api gateway or kong do in production systems.</p><h3>2. relay-backend (api + worker)</h3><p>this service was responsible for validating incoming relay requests and queuing them for execution. it had two components: an api and a worker.</p><p><strong>checker api</strong> (synchronous validation layer):</p><p>when a relay request arrived from the gateway, the checker api ran a series of checks:</p><ul><li><strong>chain support check</strong>: is this chain supported by the platform?</li><li><strong>simulation</strong>: simulate the transaction using eth_call to check if it would revert. catching reverts before submission saves gas and prevents wasted execution.</li><li><strong>balance check (for sponsoredCall)</strong>: query the fee abstraction service to verify the sponsor has enough balance in their gas tank to cover the estimated fee.</li><li><strong>contract verification (for callWithSyncFee)</strong>: validate that the target contract would actually pay back the relayer inline.</li></ul><p>if all checks passed, the checker api queued a task to the worker via bullmq (backed by redis).</p><p><strong>checker worker</strong> (async processing layer):</p><p>the worker picked up tasks from the bullmq queue and was responsible for handing them off to the executor. the exact internal logic of the worker is fuzzy, but the handoff to the executor happened via a rabbitmq queue, with an http call as a fallback mechanism.</p><p>if a task failed to execute, it was retried using bullmq’s built-in retry logic until it hit maxRetry, at which point it was marked as failed.</p><p><strong>learning:</strong> separating the synchronous validation (api) from the async processing (worker) is a really important pattern. the api can respond quickly to the caller (“your task is queued”) without blocking on execution, and the worker can take its time, handle retries, and deal with downstream failures gracefully. this is essentially the command pattern combined with a job queue. bullmq’s built-in retry with backoff means you don’t have to write retry logic yourself, which is a big deal at scale.</p><p><strong>learning:</strong> the two-queue setup (bullmq internally, rabbitmq externally) is also notable. bullmq over redis is lightweight and fast for intra-service task passing. rabbitmq is more robust for inter-service communication where you need durable messaging, topic-based routing, and decoupled consumers. using the right tool for each layer matters.</p><h3>3. executor</h3><p>the executor was the service that actually submitted transactions on-chain. it was the most infrastructure-heavy service in the relay stack.</p><p><strong>eoa wallet pool:</strong></p><p>the executor managed a pool of funded EOA (externally owned account) wallets per chain. these wallets were the actual signers that broadcast transactions to the network.</p><p>the wallets were kept funded automatically using the platform’s own automation infrastructure, which is a nice example of dogfooding: using your own product to maintain your own infrastructure.</p><p><strong>nonce management and gas pricing:</strong></p><p>the executor handled nonce management internally to avoid nonce collisions across concurrent transactions on the same wallet. it also fetched gas prices from on-chain oracles rather than relying solely on the rpc’s eth_gasPrice. (specific implementation details of the nonce locking mechanism are unclear.)</p><p><strong>per-chain fee logic:</strong></p><p>one of the more complex parts of the executor was handling fee estimation correctly across different chain types. two chain architectures required special handling:</p><p><strong>op stack chains (optimism, base, etc):</strong></p><p>transactions on op stack have two fee components:</p><ul><li>l2 execution fee: gas used * l2 gas price</li><li>l1 data fee: the cost of posting the transaction’s calldata to ethereum mainnet, proportional to the byte size of the serialized tx</li></ul><p>op stack exposes a precompile contract called GasPriceOracle at address 0x420000000000000000000000000000000000000F. calling getL1Fee(bytes calldata _data) on it returns the l1 component for a given transaction. the executor had to call this precompile to get the full cost estimate before deciding if a sponsored transaction was within the sponsor&#39;s budget.</p><p>total fee = l2 execution fee + l1 data fee</p><p><strong>arbitrum:</strong></p><p>arbitrum’s fee model is more subtle. fees are inherently two-dimensional (l2 computation + l1 calldata cost) but ethereum’s transaction format is one-dimensional (gas_limit * gas_price). arbitrum resolves this by inflating the gas limit field to absorb both dimensions:</p><pre>gas_limit = l2_gas_used + (l1_calldata_price * l1_calldata_size) / l2_gas_price</pre><p>the gas price returned by arbitrum’s rpc is just the l2 gas price. the l1 cost is encoded into the gas limit estimate. this creates a counterintuitive behavior: when l2 gas price rises, the reported gas limit actually decreases (because the l1 cost denominator gets larger), while the total fee stays roughly the same.</p><p>the practical implication for the executor was that on arbitrum, eth_estimateGas returns a composite gas limit, not a pure computation estimate. a stale estimate from a volatile l2 gas price moment could be wrong by the time the tx was submitted. this required the executor to be aware of which fee model a given chain used.</p><p><strong>learning:</strong> building for multiple chains means building for multiple execution environments, not just multiple rpc endpoints. op stack and arbitrum have meaningfully different fee models, and getting fee estimation wrong on a relay service has direct financial consequences. the executor needed per-chain configuration that told it which fee model to apply. this is a good example of how abstraction breaks down at the edges: “just submit a transaction” is not a single operation when you’re operating across 50+ chains.</p><h3>4. fee abstraction service (gas tank)</h3><p>this was the accounting and fee management layer. it handled the financial side of sponsored transactions and was composed of four components:</p><ul><li><strong>gastank-listener</strong>: listened for on-chain deposit events into gas tank contracts. when a sponsor deposited funds, this service picked it up and updated the internal balance record.</li><li><strong>executor-listener</strong>: listened for transaction confirmation events from the executor (via rabbitmq). when a sponsored tx was confirmed on-chain, this triggered the settlement process.</li><li><strong>settlement</strong>: did the actual fee deduction from the sponsor’s balance. calculated how much gas was used, what the fee was, and decremented the balance accordingly.</li><li><strong>api</strong>: exposed balance query endpoints, used by the checker-api to validate sponsor balance before accepting a task.</li></ul><p><strong>learning:</strong> this design is a good example of event-driven accounting. rather than doing synchronous balance updates inline with execution, each stage publishes events and the accounting layer reacts asynchronously. this keeps the execution path fast and lets the accounting layer handle its own consistency guarantees independently.</p><h3>5. status service (api + listener)</h3><p>the status service tracked the full lifecycle of every relay transaction and exposed that to users.</p><p><strong>status listener:</strong></p><p>the listener consumed messages from rabbitmq (topic exchange) published by the executor, checker-backend, and other services. the message types it handled included:</p><ul><li>checkPending: task received, validation in progress</li><li>execPending: task passed checks, queued for execution</li><li>execSuccess: transaction confirmed on-chain</li><li>waitingForConfirmation: transaction submitted, waiting for block confirmation</li><li>cancelled: task was cancelled</li><li>expired: task exceeded its validity window</li><li>notFound: task id not recognized</li></ul><p>on receiving a message, the listener wrote the status update to redis first (cache), then persisted it to the database asynchronously. the cache-first write meant users querying for status got a fast response without waiting for a db write.</p><p>the listener also managed websocket connections, pushing real-time status updates to connected clients as messages arrived. this avoided users needing to poll.</p><p><strong>status api:</strong></p><p>exposed two interfaces: a rest endpoint for polling-based status queries (reads from redis cache), and websocket support for push-based real-time updates.</p><p><strong>learning:</strong> the pattern here is write-through caching with async persistence. redis is fast but volatile, the db is durable but slower. by writing to redis first, you optimize for the common case (user querying status right after submission) and let the db write happen in the background. this is a well-known pattern but seeing it in a production context makes it concrete.</p><p><strong>learning:</strong> the dual interface (rest + websocket) on the same service is worth noting. for transaction status specifically, websockets are the right ux because users don’t want to poll every 500ms. but you still need the rest endpoint for one-off queries or clients that don’t support ws. supporting both from the same api layer is a practical production decision.</p><h3>6. usage tracker</h3><p>i worked on one specific feature here: post-execution transaction simulation via tenderly. after a transaction was executed on-chain (successful or failed), users could trigger a tenderly simulation of the same transaction to get a detailed execution trace. this was useful for debugging failed or reverted transactions.</p><p>the broader internals of this service are outside the scope of what i worked on directly, so i’m keeping this section minimal.</p><h3>end-to-end flow: sponsoredCall</h3><p>putting it all together, here is what happened when a developer called sponsoredCall:</p><ol><li>request hits the <strong>api-gateway</strong>, which validates the api key, checks rate limits, and routes to the checker backend</li><li><strong>checker api</strong> simulates the transaction, checks the sponsor’s gas tank balance, verifies chain support</li><li>if checks pass, checker api enqueues a task to the <strong>checker worker</strong> via bullmq</li><li><strong>checker worker</strong> picks up the task and hands it off to the <strong>executor</strong> via rabbitmq (http fallback if queue unavailable)</li><li><strong>executor</strong> selects a wallet via round robin, estimates gas (applying the correct fee model for the target chain), and submits the transaction on-chain</li><li>throughout this process, each stage publishes status events to rabbitmq</li><li><strong>status listener</strong> consumes these events, writes to redis cache and db, and pushes updates to any connected websocket clients</li><li><strong>fee abstraction executor-listener</strong> picks up the confirmation event, triggers <strong>settlement</strong> to deduct the fee from the sponsor’s gas tank balance</li><li>user can query status via rest or receive it in real time via websocket</li></ol><h3>broader learnings</h3><p><strong>microservices are a tradeoff, not a default answer.</strong> yes, having separate services means you can scale the executor independently from the status service, and a bug in the usage tracker doesn’t take down the executor. those are real benefits at scale. but the operational cost is significant. to work on any single feature end-to-end, you often need 5+ services running locally. debugging a bug that spans the checker api, rabbitmq, the executor, and the status listener is genuinely painful. shipping a feature that touches multiple services means coordinating deployments, versioning message contracts, and making sure nothing breaks at the boundaries. a well-structured monorepo can give you a lot of the code organization benefits without that overhead, especially early on. microservices make sense when the scaling and team autonomy arguments are real, not as a default architectural choice.</p><p><strong>event-driven architecture is powerful but adds observability requirements.</strong> rabbitmq topic exchanges decouple services cleanly, but debugging a flow that spans 5 services and 2 message queues without proper tooling is a nightmare. correlation ids across every log line, queue depth monitoring, and distributed tracing are not optional in this kind of system. they are the only way to answer “why did this transaction get stuck” without spending hours grepping through logs across multiple services.</p><p><strong>the financial consequences of bugs are real.</strong> a fee estimation bug in the executor on a high-volume chain isn’t just a code error, it’s money lost. this kind of system requires more careful handling of edge cases (chain-specific fee models, gas price volatility, wallet nonce collisions) than a typical web backend. the stakes change how you think about testing and defensive coding.</p><p><strong>abstractions break down at the edges.</strong> “submit a transaction” sounds simple until you’re doing it across 50+ chains with different fee models, finality assumptions, and rpc behaviors. the executor had to know about each chain’s quirks explicitly. this is a recurring theme in multi-chain infrastructure: the abstraction layer is always thinner than you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e2eac27400f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How PancakeSwap Built a DEX for the Other 4 Billion]]></title>
            <link>https://medium.com/@anirudhmakhana/how-pancakeswap-built-a-dex-for-the-other-4-billion-ff2abd58c037?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2abd58c037</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 09:42:35 GMT</pubDate>
            <atom:updated>2026-04-22T09:48:48.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>PancakeSwap is one of the largest decentralized exchanges by volume globally. It processed $2.36 trillion in trades in 2025, and served 35 million unique traders across 10 blockchains. What started as a simple AMM on Binance Smart Chain in 2020 has grown into one of the most used financial protocols in crypto, with a product suite spanning spot trading, perpetuals, liquidity farming, gamified engagement, and AI agent tooling. This piece is a product analysis of how PancakeSwap actually works, who uses it, how it makes money, and what its product decisions reveal about a distribution strategy that has quietly made it one of the largest DEXs in the world.</p><h3>Prerequisites and Key Terms</h3><p>This article covers some DeFi-specific concepts. Here is a quick reference before diving in.</p><p><strong>AMM (Automated Market Maker):</strong> A type of DEX that uses liquidity pools and a mathematical formula to price trades, instead of a traditional order book. Users trade against the pool, not against other users directly.</p><p><strong>Liquidity Pool:</strong> A smart contract holding two tokens (e.g. BNB and USDC) that users can trade against. Liquidity providers deposit both tokens and earn a share of trading fees.</p><p><strong>Liquidity Provider (LP):</strong> Someone who deposits tokens into a liquidity pool to earn fees. In return they receive LP tokens representing their share of the pool.</p><p><strong>Impermanent Loss:</strong> The temporary loss an LP experiences when the price ratio of their deposited tokens changes. The more the ratio moves, the more value is lost relative to simply holding the tokens.</p><p><strong>APR (Annual Percentage Rate):</strong> The yearly return on a deposit, not accounting for compounding. High APRs in DeFi are often subsidized by token emissions rather than organic fee revenue.</p><p><strong>Perpetual Futures (Perps):</strong> A derivative product that lets you bet on whether an asset’s price goes up or down using borrowed capital (leverage), with no expiry date. Gains and losses are amplified by the leverage multiplier.</p><p><strong>Leverage:</strong> Borrowed capital that amplifies both gains and losses. At 10x leverage, a 10% price move in your favor doubles your money. A 10% move against you wipes it out entirely.</p><p><strong>Liquidation:</strong> When a leveraged position is automatically closed because losses have consumed the collateral. At 1001x leverage, a 0.1% adverse move triggers liquidation.</p><p><strong>TWAP (Time Weighted Average Price):</strong> A trading strategy that splits a large order into smaller chunks executed over time. Used by large traders to reduce the price impact of a single large swap.</p><p><strong>CAKE:</strong> PancakeSwap’s native governance token. Used for staking, governance voting, and is regularly bought back and burned using protocol fee revenue.</p><p><strong>TVL (Total Value Locked):</strong> The total value of assets deposited in a protocol’s smart contracts. A common measure of a DeFi protocol’s size.</p><p><strong>Gas fees:</strong> Transaction fees paid to use a blockchain network. On Ethereum mainnet these peaked above $50 per transaction in 2021. On BSC they remain fractions of a cent.</p><h3>Context: Where PancakeSwap Came From</h3><p>PancakeSwap launched in September 2020 on Binance Smart Chain. The pitch was simple: Uniswap-style AMM trading on a faster, cheaper chain. At the time, Ethereum gas fees were pricing out a huge portion of potential DeFi users. Paying $50 in gas to swap $200 of tokens did not make economic sense for most people. BSC offered sub-cent transactions. The founding insight was not about building better technology. It was about access.</p><p>That insight shaped every product decision that followed. PancakeSwap today looks sprawling, multilingual, and multi-product. The Ethereum-native crowd reads this as a lack of focus. A more accurate read is that it reflects a different target market entirely.</p><h3>The Product: Five Products, One Kitchen</h3><p>Open PancakeSwap today and the nav reads: Trade. Perps. Earn. Play. AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5ms5JYhcqhP6ESwyhwfkg.png" /></figure><p>Five distinct product categories on one platform. Each tab is not just a feature. It is a deliberate decision about which user to acquire and retain.</p><h3>1. Trade</h3><p>The Trade tab has three tools: Swap, Limit Orders, and TWAP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KeoxNi9N9aArnSzVI4FxA.png" /></figure><p>Swap is the core product. Token A in, token B out, at the current AMM price routed through PancakeSwap’s liquidity pools across V2, V3, Infinity, and StableSwap pool types. It accounts for the majority of platform usage and was the foundation that built PancakeSwap’s initial liquidity depth on BSC.</p><p>Limit orders let users set a target price and wait for execution. The order sits off-chain and executes on-chain when the market hits the specified price, using a keeper network to trigger the transaction.</p><p>TWAP (Time Weighted Average Price) splits large orders into smaller child orders executed at regular intervals over a defined time window. This reduces price impact for large trades by spreading execution across time rather than hitting the pool with a single large swap that would move the price against the trader.</p><p>The notable product decision here is making all three tools available directly in the UI. Most major DEXs expose TWAP as a price oracle primitive for developers to query, not as a user-facing execution tool. Uniswap’s TWAP, for example, is an on-chain data feed that other protocols use for pricing. PancakeSwap made a different call: put the execution tool directly in the interface so any user can access it. A retail user swapping $50 of BNB and an institution splitting a $500,000 order over eight hours are using the same product surface. That is an unusual product decision and a deliberate one.</p><h3>2. Perps</h3><p>Perpetual futures on PancakeSwap let users take leveraged directional bets on BTC, ETH, and other assets without an expiry date.</p><p>The mechanics work like this: a user deposits collateral (USDT), selects a direction (long or short), and chooses a leverage multiplier. At 10x leverage, a $1,000 deposit controls a $10,000 position. If the asset moves 10% in the chosen direction, the user earns $1,000, doubling their money. If it moves 10% against them, the collateral is gone and the position is liquidated automatically.</p><p>PancakeSwap’s perps offer leverage up to 1001x. At that level, a 0.1% adverse price movement is enough to trigger liquidation. The leverage slider on the interface is labeled “Degen” at the high end. This is not ironic. It is accurate product communication: the label tells users exactly what they are doing without requiring a separate disclaimer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*-zp_6_JqbORHyFx3zPme-g.png" /></figure><p>The underlying infrastructure is serious despite the unserious branding. Price feeds are powered by Pyth Network, which aggregates real-time data from institutional trading firms and major exchanges to provide low-latency, manipulation-resistant price oracles on-chain. The product aesthetic is deliberately casual. The technical foundation underneath it is not.</p><p>PancakeSwap perps also offer fixed expiry contracts alongside the perpetual positions. This gives traders the ability to express time-bounded directional views, similar to traditional options, in addition to open-ended leveraged exposure.</p><p>The perps product generates significant trading volume and fee revenue. Every leveraged trade pays a fee. That fee flows back into the CAKE burn mechanism. The degen trader using 1001x leverage is, in a real sense, subsidizing the liquidity that makes the retail swapper’s $50 trade execute cleanly.</p><h3>3. Earn</h3><p>The Earn tab is where the product complexity is most visible. It has two main sections: Farm/Liquidity and Syrup Pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_CBUZ_cwZwzzlZNufmOPw.png" /></figure><p>Farm/Liquidity lets users deposit token pairs into liquidity pools and earn a share of trading fees from every swap routed through their position. PancakeSwap currently has four pool types live simultaneously: V2 (traditional x*y=k AMM), V3 (concentrated liquidity with custom price ranges), Infinity (their newest liquidity model with flexible fee management), and StableSwap (optimized for stable pairs with lower slippage). A fifth type, CLAMM (Concentrated Liquidity AMM), also appears across multiple chains.</p><p>Syrup Pools are simpler. Deposit CAKE, earn other project tokens. Single-asset staking with rewards distributed by partner protocols looking for distribution and liquidity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdOH8cocRDKtt8oiq2cP4g.png" /></figure><p>The Earn tab serves two very different users: sophisticated LPs who understand concentrated liquidity ranges, impermanent loss, and fee tier selection, and passive users who see a high APR number and deposit. <em>The product currently does not distinguish clearly between these two users at the point of decision. That gap is covered in the Honest Questions section.</em></p><h3>4. Play</h3><p>The Play tab has two products: Prediction and Lottery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vW9PV6zh0ccYcO1oYKY0XQ.png" /></figure><p>Prediction lets users bet on whether BNB, BTC, or ETH price will be higher or lower at the end of a 5-minute window. Lottery runs periodic prize draws funded by ticket sales. The prize pool at time of writing is $31,809.</p><p>For reference, a single Polymarket market on Strait of Hormuz shipping traffic had $18 million in volume on the same day. PancakeSwap’s lottery, featured prominently in the main navigation, has a $31K prize pool.</p><p>Play is the most engagement-driven section of the product. The design is deliberate: purple background, animated stars, countdown timers. It is built to drive repeat visits and CAKE consumption, not to serve sophisticated traders. That is a valid product goal. Retention through gamification is a real mechanism, especially for retail users who are not actively farming or trading perps.</p><p>Separately, PancakeSwap has incubated Probable, an independent prediction market platform backed by YZi Labs. Probable is positioned as a direct competitor to Polymarket and Kalshi, targeting serious prediction market users. The fact that PancakeSwap is building Probable externally while maintaining its own simpler Prediction product internally raises a legitimate question: does the team consider its own Play prediction product too lightweight for the serious prediction market segment? Building a more capable version outside the main product suggests the answer is yes.</p><h3>5. AI</h3><p>The AI tab launched in March 2026 and is the most strategically significant product in the suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hm17ih3fHDxEC5ohs7915A.png" /></figure><p>PancakeSwap AI introduces a set of modular “Skills”: pre-built tools that allow AI coding agents (Claude Code, Cursor, Copilot, Windsurf, and others) to plan DeFi operations across PancakeSwap’s ecosystem. The initial three skills are a Swap Planner, a Liquidity Planner, and a Farming Planner.</p><p>The architecture is worth understanding in detail. The system does not give agents direct execution rights over a user’s wallet. Instead, agents query on-chain data, run simulations, and output deep links that route to the PancakeSwap web app for the user to confirm and sign. This is a deliberate trust boundary: agents plan, humans execute. It reduces the risk surface of autonomous fund management while still enabling full workflow automation up to the signing step.</p><p>By end of March 2026, four additional skills had shipped: showing harvestable fees across farms, tracking rewards across positions, generating ready-to-use swap code, and Hub API integration. Third-party integrations have followed quickly. Pieverse integrated PancakeSwap AI Skills into WhatsApp, Telegram, Kakao, and Line. Fourmeme enables agents to continue graduated tokens through PancakeSwap AI Skills. Orbofi lets users create tokenized agents that automatically interact with the PancakeSwap ecosystem.</p><p>The strategic bet is clear: PancakeSwap wants to be the DEX that AI agents call by default when they need to execute a swap, plan an LP position, or optimize a yield strategy. As AI agents increasingly manage on-chain activity on behalf of users, the DEX with the best agent tooling becomes the default routing layer for a large share of future DeFi volume. The AI tab is not a consumer feature. It is infrastructure for the next distribution channel.</p><h3>The Numbers</h3><p>Volume rankings for DEXs depend heavily on which data platform you use and when you look, and it is worth being transparent about that.</p><p>On DefiLlama’s spot DEX rankings as of April 2026, Uniswap leads with approximately $2.2 billion in 24-hour spot volume. PancakeSwap sits at number two with approximately $967 million in 24-hour spot volume. On Dune Analytics over the same period, PancakeSwap has shown significantly higher numbers, at times ranking number one globally.</p><p>The discrepancy comes down to methodology. DefiLlama separates spot swaps, perpetuals, and aggregator volume into distinct dashboards. The spot DEX view excludes perps volume entirely. Dune dashboards often count combined volume across pool types and may capture different chain activity at different update frequencies. PancakeSwap’s perps product adds significant notional volume that counts differently depending on the platform. Additionally, PancakeSwap’s spot volume is heavily influenced by BSC meme coin activity, which creates sharp spikes that can push its rankings above Uniswap temporarily before normalizing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZXrAdgzyV7CABdg8ieCvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zs0rkv8kohujyJfaki73bg.png" /></figure><p>What both data sources agree on: PancakeSwap and Uniswap are in a different tier from every other DEX. The third-ranked protocol on DefiLlama, Fluid, has approximately $2.9 billion in 7-day volume.</p><p>Over 2025 as a whole, PancakeSwap processed $2.36 trillion in trading volume across spot and derivatives. That is a 619% increase year over year. The platform served 35.37 million unique traders and expanded to 10 blockchains. Whether it sits at number one or number two on any given day matters less than the structural fact: a platform that launched on a cheaper chain in 2020 now competes directly with the protocol that invented the AMM model.</p><p>The Base expansion shows how the multichain strategy compounds over time. PancakeSwap crossed $100 billion in cumulative volume on Base with 3.5 million users. Its cbBTC/WETH pool was the highest volume pool on Base across all DEXs in March 2026. Its USDC/WETH pair consistently recorded the highest volumes on Base, reaching $78 million in 24-hour volume on select days.</p><p>TVL sits at approximately $2.38 billion, which is lower than Uniswap’s locked capital. This reflects the model. PancakeSwap optimizes for active trading volume rather than passive deposits. High capital turnover on a smaller TVL base is a deliberate design outcome, not a weakness.</p><h3>The Distribution Insight</h3><p>The platform is available in over 12 languages including Vietnamese, Filipino, Hindi, Bahasa Indonesia, Portuguese, and Thai. Community meetups ran in Ho Chi Minh City and Sao Paulo in March 2026. The Telegram bot lets users swap over 3,000 tokens without opening a browser. AI integrations extend to WhatsApp, Kakao, and Line, messaging apps with dominant adoption across Southeast Asia and East Asia that most Western DeFi products have never prioritized.</p><p>None of this is cosmetic localization. It is the core distribution strategy.</p><p>The users PancakeSwap serves in Vietnam, Brazil, Indonesia, and the Philippines could not participate in Ethereum DeFi during the 2021 and 2022 gas fee peaks. A $50 gas fee does not inconvenience a user transacting $100. It makes the transaction economically impossible. BSC’s sub-cent fees solved this problem directly. BSC was not a compromise for PancakeSwap’s target users. It was the prerequisite.</p><p>The multichain expansion follows the same logic. Every chain PancakeSwap has added, including Solana, Base, Arbitrum, Monad, and opBNB, is a chain with lower fees, faster finality, and growing user bases in markets where gas cost is a real constraint. Each new chain is a new distribution surface for users who cannot or will not pay Ethereum mainnet costs.</p><p>The Telegram bot strategy is the clearest expression of this philosophy. Telegram has over 900 million monthly active users, with high density across Southeast Asia, Eastern Europe, and Latin America. Building a swap bot inside Telegram means meeting users inside an app they already use daily. No new wallet to set up. No browser extension to install. No onboarding modal to navigate. The reduction in friction is structural, not cosmetic.</p><p>This is why PancakeSwap’s user base is as wide as it is. The geographic breadth came first. The product breadth followed the users.</p><h3>The User Range: Five Products, Five People</h3><p>Spend time across PancakeSwap’s product suite and at least five distinct user types become visible, all sharing one platform.</p><p><strong>The retail swapper.</strong> A user in Vietnam or Brazil converting $50 of BNB to USDC. They need fast execution, low fees, and a simple interface. They found PancakeSwap through a Telegram group or a community referral. They do not read documentation.</p><p><strong>The yield farmer.</strong> A user depositing token pairs into V3 or Infinity pools to earn trading fees and CAKE rewards. They track APR across pools, understand impermanent loss in concentrated liquidity positions, and move capital based on incentive changes. They are in the Earn tab multiple times a week.</p><p><strong>The degen trader.</strong> A user opening leveraged positions on BTC or ETH perps. They selected the leverage slider deliberately. They understand liquidation risk. Their trading activity generates volume and fee revenue that flows back into CAKE burns and LP returns.</p><p><strong>The institutional LP.</strong> A protocol or fund providing concentrated liquidity to USDC/WETH on Base, capturing fees from tens of millions in daily volume. They use CLAMM with custom price ranges and harvest rewards through the position management interface. They are indifferent to the lottery.</p><p><strong>The developer or agent builder.</strong> A team integrating PancakeSwap AI Skills into an application so their AI agent can route swaps, plan LP positions, or optimize farming strategies on behalf of end users. They interact with PancakeSwap through an API and a markdown skills file. They never see the Play tab.</p><p>These five users share almost nothing in terms of risk tolerance, technical sophistication, geographic location, or product expectations. What they share is access to the same underlying liquidity pools and the same smart contract infrastructure.</p><p>This is the product question that requires an honest answer: how does one platform coherently serve all five?</p><p>The honest answer is that PancakeSwap does not fully resolve this tension. It manages it through architecture. The retail swapper and the institutional LP are not using the same product features and rarely interact with each other’s part of the platform. The degen trader’s leveraged volume deepens the liquidity that the institutional LP relies on for fee income. The yield farmer’s deposited capital is what allows the retail swapper’s $50 trade to execute with minimal slippage. The product is not a unified experience. It is a shared liquidity layer with five different front doors.</p><h3>Closing</h3><p>PancakeSwap did not reach $2.36 trillion in annual volume by building a better Uniswap. It got there by targeting a different user in a different market with a different set of constraints, and then expanding aggressively from that base.</p><p>The lottery exists because gamification drives retention for users who are not actively optimizing yield. The Degen slider exists because speculative volume generates fees that deepen liquidity for every other user type. The Telegram bot exists because most of PancakeSwap’s target users will not install a browser extension. The AI Skills exist because the next distribution channel for DeFi volume may not be human users at all.</p><p>Each of these decisions looks unrelated in isolation. Together they describe a platform that has been executing one consistent strategy since 2020: find the users the high-gas protocols cannot serve, build the product they can actually use, and keep fees low enough that volume compensates for thin margins.</p><p>Whether that strategy holds as DeFi matures is the most interesting product question PancakeSwap faces in 2026. Gas fees on L2s are approaching zero. The access advantage that BSC provided is narrowing. The next phase requires a different answer to the question of who PancakeSwap is for.</p><p>The kitchen is shipping. The question is whether the menu still makes sense.</p><h3>Sources</h3><p><strong>Context section</strong></p><p>“PancakeSwap launched in September 2020 on Binance Smart Chain” Source: Messari — <a href="https://messari.io/project/pancakeswap/profile">https://messari.io/project/pancakeswap/profile</a></p><p>“Ethereum gas fees peaked at $53 during the most congested period, with a single Uniswap swap costing over $200 during peak hours in May 2021” Source: CoinLedger — <a href="https://coinledger.io/research/ethereum-transaction-fees-and-gas-prices-trends-and-insights">https://coinledger.io/research/ethereum-transaction-fees-and-gas-prices-trends-and-insights</a> Source: CoinLaw — <a href="https://coinlaw.io/ethereum-gas-fee-history/">https://coinlaw.io/ethereum-gas-fee-history/</a></p><p><strong>The Numbers section</strong></p><p>“$2.36 trillion in trading volume in 2025, 619% increase year over year, 35.37 million unique traders” Source: PancakeSwap 2025 review — <a href="https://insidecryptoreview.com/en/dex/pancakeswap">https://insidecryptoreview.com/en/dex/pancakeswap</a></p><p>“37.8% DEX market share, $26.7B 7-day volume, Uniswap at $17.1B” Source: Dune Analytics DEX rankings dashboard — <a href="https://dune.com/dune/dex-metrics">https://dune.com/dune/dex-metrics</a></p><p>“$100B cumulative on Base, 3.5M users, cbBTC/WETH #1 pool on Base” Source: PancakeSwap March 2026 recap — <a href="https://blog.pancakeswap.finance/">https://blog.pancakeswap.finance</a></p><p><strong>Distribution section</strong></p><p>“Telegram has over 900 million monthly active users” Source: Telegram official stats — widely reported, most recent citation via Cointelegraph</p><p>“PancakeSwap Telegram bot supports over 3,000 tokens” Source: Cointelegraph — <a href="https://cointelegraph.com/news/pancakeswap-telegram-bot-crypto-trading-bnb">https://cointelegraph.com/news/pancakeswap-telegram-bot-crypto-trading-bnb</a></p><p>“Community meetups in Ho Chi Minh City and Sao Paulo, March 2026” Source: PancakeSwap March 2026 recap — <a href="https://blog.pancakeswap.finance/">https://blog.pancakeswap.finance</a></p><p><strong>AI section</strong></p><p>“PancakeSwap AI launched March 4, 2026 with Swap Planner, Liquidity Planner, Farming Planner” Source: CryptoTimes — <a href="https://www.cryptotimes.io/2026/03/04/pancakeswap-debuts-ai-skills-to-power-autonomous-defi-agents/">https://www.cryptotimes.io/2026/03/04/pancakeswap-debuts-ai-skills-to-power-autonomous-defi-agents/</a></p><p><strong>Play section</strong></p><p>“Probable incubated by PancakeSwap, backed by YZi Labs” Source: The Block — <a href="https://www.theblock.co/post/382685/pancakeswap-prediction-market-probable-bnb">https://www.theblock.co/post/382685/pancakeswap-prediction-market-probable-bnb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2abd58c037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[70% of Polymarket Users Never Deposit. Here’s What the Data Says.]]></title>
            <link>https://medium.com/@anirudhmakhana/70-of-polymarket-users-never-deposit-heres-what-the-data-says-85e236ba8c72?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/85e236ba8c72</guid>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[polymarket]]></category>
            <category><![CDATA[prediction-markets]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 11:03:40 GMT</pubDate>
            <atom:updated>2026-04-20T11:03:40.282Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A product teardown by someone learning product management in public — all views are my own, all mistakes are part of the process.</em></p><p>I got laid off recently. Close to three years at <a href="http://gelato.cloud/">Gelato</a> — first in DevRel talking to enterprise clients like GMX, MoonPay, and Kraken, then transitioning into backend infrastructure engineering, building relay systems that processed millions of transactions across 50+ chains. Good years. Hard years. Ones I’m genuinely proud of.</p><p>But somewhere in those three years, something shifted in me.</p><p>There was a moment working with <a href="https://gmx.io/#/">GMX</a> — they were constantly sending feedback on our status API. I was heads down in the engineering, optimizing the thing, making it faster. But the feedback kept coming and it wasn’t about performance. It was about context. About what information <em>they</em> needed to run their business, not just what was technically correct to return. We made changes to the API based purely on those conversations — and those changes ended up helping every single customer on the platform, not just GMX.</p><p>That’s when it hit me. I didn’t just want to build the thing. I wanted to build the thing with the right context. I wanted to sit at the intersection of what users actually need, what the business is trying to do, and what engineering can realistically ship. That’s not purely an engineering job. That’s product.</p><p>So here I am. Laid off, 25 years old, based in Bangkok, and decided that instead of just applying to jobs, I’m going to learn product management in public. Every day for the next 30 days, I’m going to pick a company — a real one, one I actually use or care about — and try to think through it like a PM would. Not perfectly. Not with insider data. But honestly, with whatever I can find publicly, and with the intellectual humility to say when I’m wrong.</p><p>Today is day 1. I picked <a href="https://polymarket.com/">Polymarket</a>.</p><h3>Why Polymarket</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUJ1bruOteHJxm2_.png" /></figure><p>Polymarket is the world’s largest prediction market. $21 billion traded in 2025. The idea is elegant: instead of pundits telling you what they think will happen, markets aggregate the wisdom of thousands of people with actual money on the line. Price becomes probability. It’s one of the most genuinely interesting products in crypto — and arguably the closest thing to PMF the space has produced. But as we’ll see, the data tells a more complicated story.</p><p>I also tried to use it today. From Bangkok. With my Rabby wallet connected.</p><p>I didn’t place a single bet.</p><p>Here’s what happened — and more importantly, here’s what the data says about why I’m probably not alone.</p><h3>What I Actually Experienced</h3><p>The moment I tried to trade, Polymarket hit me with a modal. Three steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqKaj8PvNp8VOIeaRGQnvQ.png" /></figure><ol><li><strong>Deploy Proxy Wallet</strong> — <em>“Deploy a smart contract wallet to enable trading”</em></li><li><strong>Enable Trading</strong> — <em>“Sign a message to generate your API keys”</em></li><li><strong>Approve Tokens</strong> — <em>“Approve token spending for trading”</em></li></ol><p>Each step has its own button. Each button requires a wallet interaction. And crucially — none of them explain <em>why</em> they exist in plain language.</p><p>I got through steps 1 and 2. When I hit step 3. Approve Tokens. I opened Rabby to sign, and there was nothing. No approval amount. No spending limit. No expiry. Just a request to approve.</p><p>I paused. And then I closed the tab.</p><p>Now, I want to be honest here: I have more context than the average user. I’ve spent three years building relay infrastructure and working with account abstraction systems. I understand what a proxy wallet is. I understand what a token approval means. And <em>I still hesitated.</em> That tells you something.</p><p>The hesitation wasn’t irrational either. A blank token approval in your wallet is genuinely ambiguous. Is this an unlimited approval? A specific amount? How long does it last? The modal doesn’t say. Rabby doesn’t surface it clearly. The mental model breaks down exactly at the moment it matters most — right before someone puts money in.</p><h3>What the Data Says</h3><p>Here’s where it gets really interesting. My experience wasn’t an edge case. Dune Analytics makes Polymarket’s onchain data public, and I spent time going through it. A few things stood out.</p><p><strong>The funded vs unfunded proxy wallet chart is the most important thing I found.</strong></p><p>As of April 2026, Polymarket has created approximately 6.5 million proxy wallets. Of those, roughly 2 million are funded. That means approximately <strong>70% of users who completed the onboarding modal — all three steps — never deposited a single dollar.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I2mXjEqKd3mVwI2dTI_00w.png" /><figcaption><a href="https://dune.com/datadashboards/polymarket-overview">https://dune.com/datadashboards/polymarket-overview</a></figcaption></figure><p>Let that sit for a second. These aren’t users who bounced on the homepage. These are users who connected their wallet, deployed a smart contract, signed a message, and went through the approval step. And then still didn’t fund.</p><p>The wallet creation charts tell a parallel story. Every spike in new wallet creation is tied to a specific event — the US election cycle in late 2024, the US relaunch in early 2026. Outside those spikes, growth is flat. Polymarket is almost entirely event-driven, and the users it acquires during events largely don’t stick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T24Jelzp3yRHL0MidR_71Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6c91MC5LpM3eEkFLGB8D-A.png" /></figure><p><strong>The bet distribution data is where things get really nuanced — and this is where I’d ask you to look at two charts side by side.</strong></p><p>Dune has two cuts of the same data: percentage of users in each betting bucket, and percentage of total volume in each bucket. The contrast is stark.</p><p>On the user side, the distribution is relatively spread out. Around 11% of users have bet between $0–$10 total. Another 11% are in the $500–$1K range. The majority of Polymarket’s user base clusters below $5K lifetime bets. Almost nobody — 0.03%, 0.01%, 0.00% — has ever bet above $2.5M.</p><p>Flip to the volume chart and the picture inverts completely. Users betting small amounts contribute essentially nothing to traded volume. Volume starts concentrating heavily only above $25K. The $5M–$10M bucket alone accounts for 12.93% of all volume. The $100M+ bucket accounts for 8.78%.</p><p>What this means in plain terms: <strong>Polymarket’s user base is mostly small bettors. Polymarket’s volume is almost entirely driven by a tiny number of whales.</strong> These are not the same product. The experience that retains a whale — deep liquidity, sophisticated order types, serious market quality — is not the same experience that converts a curious first-timer into a funded account.</p><p>This creates a genuine strategic tension that I think is at the heart of the product problem. If you optimize onboarding for retail, you might bring in millions of small bettors who collectively move the needle very little on volume. If you optimize for whales, you ignore the 70% who created a wallet and walked away — and you remain dangerously dependent on a tiny user segment.</p><p><strong>What this means together:</strong> Polymarket has a top-of-funnel that looks healthy on paper (millions of wallets created) but a conversion and segmentation problem that runs all the way through the funnel. Users sign up, don’t fund, and those who do fund are overwhelmingly whales, not retail.</p><p><em>NOTE: I want to be clear about the limits of my analysis here. I don’t have internal drop-off data. I don’t know what % of users abandon at each specific step of the modal. I don’t have session recordings or user interview transcripts. A real PM would have all of this before drawing conclusions. I’m working from public signals and my own experience, and I could be wrong about causality even if the correlation is real.</em></p><h3>The Technical Problems (And Possible Directions)</h3><p><strong>Problem 1: The token approval UX creates silent trust erosion</strong></p><p>When a user hits “Approve Tokens” and their wallet shows nothing meaningful — no amount, no expiry — it creates a moment of doubt. For crypto-native users, that doubt might be familiar enough to push through. For everyone else, it’s a reason to stop.</p><p>One direction worth exploring here is <strong>EIP-2612 (Permit)</strong>. Instead of a standard ERC-20 approval transaction, Permit lets users sign an offchain message that includes the exact amount, the recipient, and an expiry timestamp. No onchain transaction required for the approval step. No ambiguity about what’s being approved. The user sees exactly what they’re signing, and the approval expires automatically.</p><p>I want to be honest about what I don’t know here: whether Polymarket’s CTF exchange and orderbook architecture can support Permit natively, and what the engineering cost of that migration would be. This isn’t a “just do this” suggestion — it’s a direction that seems worth a conversation between product and engineering. What I do feel confident about is the problem: silent approvals erode trust, and trust is everything when you’re asking someone to put real money into a smart contract.</p><p><strong>Problem 2: The proxy wallet architecture creates unnecessary friction</strong></p><p>Polymarket requires a separate smart contract proxy wallet to be deployed before trading. This is an architectural requirement of their CTF exchange — it’s not arbitrary. But from a user perspective, it adds a deployment step that feels alien if you’ve never interacted with a smart contract before.</p><p><strong>EIP-7702</strong>, which shipped with Ethereum’s Pectra upgrade, opens up an interesting direction here. It allows an existing EOA (a regular wallet like Rabby or MetaMask) to temporarily adopt smart contract behavior via a delegation signature — without deploying a separate contract. In theory, this could collapse the “Deploy Proxy Wallet” step entirely. Your existing wallet becomes the proxy.</p><p>But I want to be careful about overstating this. 7702 wallet support is still early. The migration from Polymarket’s current proxy architecture would be a significant engineering undertaking. And the core users — crypto natives — have already deployed their proxy wallets and don’t feel this friction anymore. The question a real PM would ask first is: what’s the actual drop-off rate at step 1 of the modal? If it’s low, this isn’t the priority.</p><p><strong>Problem 3: The real problem might not be the modal at all</strong></p><p>Here’s the most honest thing I can say: the 70% unfunded wallet stat suggests the modal isn’t where most people are dropping off. They’re completing the modal and <em>then</em> not funding.</p><p>Which means the question isn’t “how do we simplify the steps.” It’s “what’s missing between wallet creation and first deposit that would make someone take out their credit card?”</p><p>Some hypotheses — and I want to be explicit that these are hypotheses, not conclusions:</p><ul><li>There’s no compelling market at the moment of signup. You’ve just deployed your wallet and the first thing you see is a geopolitical shipping route question with $18M volume. Cool, but why would <em>I</em> have edge on that?</li><li>There’s no low-stakes entry point. No paper trading, no $1 minimum market, no “try it with $5” moment that builds confidence before real money goes in.</li><li>The funding mechanism itself requires USDC, which requires already being in crypto. For anyone coming from outside the ecosystem, the path to first dollar in is long.</li><li>The context layer is underdeveloped. Polymarket has started adding news feeds to markets, and even partnered with X and Grok in 2025 to surface social signals. But the execution feels incomplete — I’d want to see real-time signals from the actual accounts that move specific markets, not just generic news headlines.</li></ul><h3>What I’d Prioritize (If I Were PM, Which I’m Not Yet)</h3><p>If I were sitting in a product review at Polymarket tomorrow, here’s roughly how I’d think about prioritization — with the explicit caveat that I’d want data before committing to any of this.</p><p><strong>High priority, lower effort:</strong> Fix the approval UX. Show users exactly what they’re approving — amount, recipient, expiry — in plain language inside the Polymarket modal itself, before they open their wallet. Don’t rely on Rabby or MetaMask to surface this clearly. Own the explanation. This doesn’t require an architectural change and directly addresses a trust gap at a critical moment.</p><p><strong>Medium priority, higher effort:</strong> Investigate the post-modal drop-off. Before building anything new, I’d want to know exactly where in the funnel the 70% are leaving. Is it the funding step? Is it the market discovery experience after funding? Is it the USDC requirement? The answer changes everything about what to build next.</p><p><strong>Longer term, worth exploring:</strong> The onboarding architecture question (7702, Permit, gasless options). These are real technical improvements but they require significant investment and the user benefit depends heavily on who the target user actually is. If Polymarket is doubling down on retail, this matters a lot. If volume is driven by whales who are already onboarded, it matters less.</p><h3>What I Learned Today</h3><p>I started this morning thinking the onboarding modal was the problem. Three steps, confusing language, web3 jargon — fix those and you fix conversion.</p><p>The data humbled me. The modal isn’t where 70% of users are dropping. They’re completing it and still not depositing. Which means the problem is harder and more interesting than I thought.</p><p>I also learned that being technically deep isn’t the same as thinking like a PM. I could have spent this whole article talking about 7702 and Permit and proxy wallet architecture. That would have been interesting to maybe 200 people. The more important question — why do millions of people create a wallet and then leave — is what actually matters.</p><p>That shift in focus, from “what can we build” to “what problem are we actually solving,” is what I’m practicing. Day 1 done.</p><p>— — —</p><p><em>This is part of my 30-day product teardown series. Every day I pick a real company and try to think through one product problem as honestly as I can. I’m not a PM yet. I’m an engineer who’s spent three years building backend infrastructure for web3 protocols and talking to enterprise clients, and who has decided that product is where I want to go next. Follow along if you’re on a similar journey, or if you just enjoy watching someone learn in public.</em></p><p><em>All views are entirely my own. All mistakes are mine too.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e236ba8c72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[rust for beginners: the mental models that made it click]]></title>
            <link>https://medium.com/@anirudhmakhana/rust-for-beginners-the-mental-models-that-made-it-click-832ee75a85a8?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/832ee75a85a8</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[solana-network]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 08:08:27 GMT</pubDate>
            <atom:updated>2026-04-02T08:08:27.264Z</atom:updated>
            <content:encoded><![CDATA[<p>beginner rust makes a lot more sense once i stop memorizing syntax and start understanding how the language thinks about data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*6yvVDv4Y6vAExXAXKrLEoQ.jpeg" /></figure><blockquote><em>quick disclaimer: i’m documenting my learning in public and this is how i currently understand rust. i’m not a rust pro yet, and i’m not pretending to be one. i care a lot about getting the fundamentals right, and i’ll keep refining this as i go deeper.</em></blockquote><p>most beginner rust content loses people because it starts with syntax instead of the model.</p><p>that is the wrong starting point.</p><p>the way i understand rust now is this:</p><p>rust is not mainly trying to give me prettier syntax. it is trying to make ownership, mutation, memory access, and validity explicit.</p><p>once that clicked for me, beginner rust stopped feeling like random compiler pain and started feeling like one coherent system.</p><p>this post is only about beginner rust. advanced rust deserves a separate follow-up because it is built on the same rules, just pushed harder.</p><h3>the main beginner mistake</h3><p>the main mistake i see beginners make, and one i made too, is trying to learn rust as a bag of features:</p><ul><li>variables</li><li>functions</li><li>structs</li><li>borrowing</li><li>lifetimes</li><li>traits</li></ul><p>that approach makes rust feel fragmented.</p><p>the better question is:</p><ul><li>what is rust actually optimizing for?</li></ul><p>my current answer is:</p><ul><li>clear ownership</li><li>safe access to data</li><li>controlled mutation</li><li>predictable memory behavior</li><li>catching bugs before runtime</li></ul><p>so beginner rust is not really about memorizing syntax. it is about learning how the language thinks about data.</p><p>underneath almost every beginner concept, rust is really asking:</p><ul><li>who owns this value?</li><li>who can read it?</li><li>who can change it?</li><li>how long is it valid?</li></ul><p>that is the model.</p><h3>what rust is optimizing for</h3><p>coming from more application-heavy ecosystems, especially in web3 where a lot of day-to-day work still happens in languages that hide more runtime detail, rust feels unusually explicit.</p><p>that explicitness is the point.</p><p>rust wants me to be honest about:</p><ul><li>whether a value is owned or borrowed</li><li>whether something can be mutated</li><li>whether that mutation is exclusive</li><li>whether a reference is still valid</li></ul><p>in a lot of other languages, i can delay these questions. in rust, the compiler forces me to answer them early.</p><p>that can feel harsh at first, but it also means the language is moving a bunch of bugs from runtime into compile time.</p><p>so if i had to explain rust simply, i’d say:</p><p>rust is a language for making the rules around data explicit.</p><h3>variables, immutability, mutability, and shadowing</h3><p>the first thing that mattered more than i expected was how rust treats variables.</p><p>variables are immutable by default:</p><pre>let x = 42;</pre><p>if i want to change a value over time, i have to opt into mutability:</p><pre>let mut total = 0;<br>total += 1;</pre><p>this seems small, but it changes how i read code.</p><p>when i see let, i assume stability. when i see let mut, i assume state evolution.</p><p>that alone makes code easier to reason about.</p><p>the mental model that clicked for me here is:</p><ul><li>mutability is about the same value slot changing over time</li></ul><p>that is why this feels natural:</p><pre>let mut total = 0;<br>total += 1;<br>total += 2;</pre><p>it is still the same conceptual thing. it is just being updated.</p><p>shadowing is different:</p><pre>let input = &quot; 42 &quot;;<br>let input = input.trim();<br>let input: i32 = input.parse().unwrap();</pre><p>the mental model i use is:</p><ul><li>shadowing is about the same name, new meaning</li><li>very often, it is really about introducing a new representation or even a new type</li></ul><p>so if mutability is:</p><ul><li>same slot, new value</li></ul><p>shadowing is:</p><ul><li>same name, new stage</li></ul><p>that distinction helped me a lot because rust uses both heavily, but for different reasons.</p><p>use mut when something is still the same thing and just changes. use shadowing when the value has been transformed into a new stage.</p><h3>stack vs heap</h3><p>this is one of those “under the hood” concepts that turns out to explain a huge part of beginner rust.</p><p>the mental model i use is:</p><ul><li>stack = desk</li><li>heap = storage room</li></ul><p>the desk is fast and tidy, but limited. the storage room is flexible, but someone has to manage it.</p><p>simple fixed-size values like integers are easy to keep on the desk. more flexible data like a String or Vec&lt;T&gt; needs heap allocation.</p><p>that is why this distinction matters:</p><pre>let x = 5;<br>let s = String::from(&quot;hello&quot;);</pre><p>x is simple. s is more involved.</p><p>the important beginner point is not memorizing layout details. it is understanding that heap-backed values introduce ownership questions.</p><p>once i understood that, the next concept made much more sense.</p><h3>ownership</h3><p>ownership is the center of beginner rust.</p><p>the mental model i use is:</p><ul><li>every value has one responsible owner</li></ul><p>that owner is responsible for cleanup.</p><p>for types like String, assignment is not “now two things casually point to the same data.” it is usually ownership transfer.</p><p>for example:</p><pre>let a = String::from(&quot;hello&quot;);<br>let b = a;</pre><p>after that, i cannot use a anymore.</p><p>the first time i hit this, it felt hostile. the second time i understood what rust was protecting me from, it started to feel clean.</p><p>the language is preventing situations where multiple bindings think they own the same heap-backed resource.</p><p>so the important beginner idea is:</p><ul><li>ownership is not about visibility</li><li>ownership is about responsibility</li></ul><p>rust is basically saying:</p><ul><li>one owner cleans this up</li><li>if ownership moves, responsibility moves</li></ul><p>once that clicked, a lot of compiler messages got less mysterious.</p><h3>borrowing and references</h3><p>of course, if everything moved all the time, rust would be impossible to use.</p><p>that is where borrowing comes in.</p><p>the mental model i use is:</p><ul><li>borrowing is lending without giving away ownership</li></ul><p>if i only need to inspect a value, i should usually borrow it instead of taking ownership.</p><p>for example:</p><pre>fn count_chars(s: &amp;str) -&gt; usize {<br>    s.chars().count()<br>}</pre><p>this function does not need to own the string. it only needs read access.</p><p>that is what &amp;t means to me:</p><ul><li>read access without ownership</li></ul><p>the thing that clicked for me is that references are not just convenience. they are part of rust’s whole safety model.</p><p>when i borrow something immutably, i am saying:</p><ul><li>i need to see this value</li><li>i do not need to own it</li><li>i am not going to mutate it</li></ul><p>that level of clarity is a big part of why beginner rust feels strict and useful at the same time.</p><h3>string vs &amp;str</h3><p>this is one of the most important beginner distinctions in rust.</p><p>the mental model i use is:</p><ul><li>String = owned text</li><li>&amp;str = borrowed view into text</li></ul><p>that means these are not interchangeable ideas:</p><pre>let owned = String::from(&quot;hello&quot;);<br>let borrowed = &quot;hello&quot;;</pre><p>String owns heap-backed text. &amp;str is a borrowed string slice.</p><p>for me, this is where rust starts teaching good API design very early.</p><p>if a function only needs to read text, it often should take &amp;str:</p><pre>fn greet(name: &amp;str) {<br>    println!(&quot;hello, {}&quot;, name);<br>}</pre><p>that is more flexible than taking String, because the function does not force ownership transfer when it does not need it.</p><p>this also made another rust habit make sense:</p><ul><li>borrowed inputs, owned outputs</li></ul><p>that pattern shows up everywhere once i start looking for it.</p><h3>mutable borrowing</h3><p>mutable borrowing is where rust gets even more explicit.</p><p>the mental model i use is:</p><ul><li>&amp;mut t = exclusive temporary control</li></ul><p>for example:</p><pre>fn add_exclamation(s: &amp;mut String) {<br>    s.push(&#39;!&#39;);<br>}</pre><p>this function is not taking ownership of the string. but it is saying:</p><ul><li>while i have this mutable reference, i need exclusive access to mutate it safely</li></ul><p>this is where one of rust’s deepest rules shows up:</p><ul><li>many readers or one writer</li></ul><p>that rule explains a lot of the language.</p><p>it is why mutable borrowing is stricter than people expect. it is also why rust can prevent a lot of nasty aliasing bugs before the program even runs.</p><p>so the compiler is not randomly blocking mutation. it is enforcing exclusivity.</p><h3>structs and enums</h3><p>once values and ownership start making sense, the next step is modeling data properly.</p><p>structs are the simple one:</p><pre>struct Rectangle {<br>    width: i32,<br>    height: i32,<br>}</pre><p>they are just named shapes for related data.</p><p>and then methods let me attach behavior:</p><pre>impl Rectangle {<br>    fn area(&amp;self) -&gt; i32 {<br>        self.width * self.height<br>    }<br>}</pre><p>that part feels familiar.</p><p>enums are where rust starts feeling more powerful.</p><p>an enum says:</p><ul><li>this value can legally be one of several shapes</li></ul><p>for example:</p><pre>enum Status {<br>    Active,<br>    Inactive,<br>}</pre><p>or with data:</p><pre>enum Message {<br>    Text(String),<br>    Quit,<br>}</pre><p>and then match forces me to handle the possibilities explicitly:</p><pre>match msg {<br>    Message::Text(text) =&gt; println!(&quot;{}&quot;, text),<br>    Message::Quit =&gt; println!(&quot;bye&quot;),<br>}</pre><p>the mental model i use is:</p><ul><li>structs model stable shapes</li><li>enums model valid alternatives</li></ul><p>this matters because rust gives me a strong tool for encoding state and avoiding invalid combinations early.</p><h3>option and result</h3><p>this is another place where beginner rust teaches good habits early.</p><p>the mental model i use is:</p><ul><li>option = a value may not exist</li><li>result = an operation may fail</li></ul><p>instead of pretending absence and failure are edge cases to deal with later, rust puts them in the type system.</p><p>option looks like:</p><pre>let first = nums.first();</pre><p>that returns:</p><ul><li>Some(value) if it exists</li><li>None if it does not</li></ul><p>result looks like:</p><pre>fn parse_number(s: &amp;str) -&gt; Result&lt;i32, std::num::ParseIntError&gt; {<br>    s.parse::&lt;i32&gt;()<br>}</pre><p>the important beginner lesson is not just “learn Option and Result syntax.”</p><p>it is:</p><ul><li>rust wants uncertainty to be explicit</li></ul><p>that is a very big design idea.</p><p>if something may not exist, the type should say that. if something may fail, the type should say that.</p><p>this is one of the places where rust feels more honest than many languages.</p><h3>why the borrow checker feels strict</h3><p>the borrow checker is famous for making beginners suffer.</p><p>the way i understand it now is:</p><p>the borrow checker is not a random barrier. it is the mechanism that enforces the rules rust cares about:</p><ul><li>ownership</li><li>valid references</li><li>controlled mutation</li><li>no unsafe aliasing in safe code</li></ul><p>the mental model i use is:</p><ul><li>the borrow checker is a compiler enforcing data access rules early instead of letting runtime bugs happen later</li></ul><p>that framing helped me a lot.</p><p>instead of reading borrow checker errors as:</p><ul><li>“the compiler hates me”</li></ul><p>i started reading them as:</p><ul><li>“the compiler is telling me my model of who owns or borrows this data is still fuzzy”</li></ul><p>that shift made the errors much more useful.</p><p>beginner rust gets easier when i stop fighting the compiler and start asking:</p><ul><li>what ownership story is my code trying to tell?</li><li>where is that story unclear?</li></ul><p>that is usually the real issue.</p><h3>how i think about learning rust correctly</h3><p>the thing that clicked for me was that beginner rust is not really a syntax course.</p><p>it is closer to learning a disciplined way of thinking about data.</p><p>so the learning loop i find most useful is:</p><ol><li>learn the concept</li><li>write the smallest example possible</li><li>explain what owns what</li><li>explain what is borrowed</li><li>explain what can mutate</li><li>explain why the compiler allows or rejects it</li></ol><p>if i cannot do that, i probably do not understand the concept yet.</p><p>the other thing i try to keep in mind is that advanced rust is not separate from beginner rust.</p><p>advanced rust is usually just beginner rust under more pressure:</p><ul><li>shared ownership</li><li>more abstraction</li><li>concurrency</li><li>lower-level memory access</li></ul><p>but the core rules are the same.</p><p>that is why i think getting the beginner concepts right matters so much.</p><h3>the compact version</h3><p>if i had to compress beginner rust into a few lines, i’d say this:</p><ul><li>variables are immutable by default</li><li>mutability is explicit</li><li>shadowing is often about changing representation or type</li><li>some values are owned, some are borrowed</li><li>String owns text, &amp;str borrows text</li><li>&amp;t means read access without ownership</li><li>&amp;mut t means exclusive temporary control</li><li>structs model stable data</li><li>enums model legal alternatives</li><li>option models absence</li><li>result models failure</li><li>the borrow checker enforces the data access rules that make the whole system work</li></ul><p>that is the beginner layer i’m trying to internalize.</p><h3>closing</h3><p>my current view is that beginner rust is mostly about ownership, borrowing, and data modeling.</p><p>if those ideas click, the language becomes much less mysterious.</p><p>and if they do not click, every advanced topic will feel harder than it really is.</p><p>so for me, the right way to learn rust is not:</p><ul><li>memorize features</li></ul><p>it is:</p><ul><li>understand the model</li></ul><p>that is the real beginner guide.</p><p>in a follow-up, i’ll go into the advanced concepts and how they grow naturally out of these beginner ones: Rc, RefCell, trait objects, threads, channels, smart pointers, and the rest.</p><h3>important source links</h3><p>these are the main Rust references i keep coming back to while learning the beginner model properly:</p><ul><li>the Rust book: <a href="https://doc.rust-lang.org/book/">https://doc.rust-lang.org/book/</a></li><li>the Rust book, variables and mutability: <a href="https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html">https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html</a></li><li>the Rust book, data types: <a href="https://doc.rust-lang.org/book/ch03-02-data-types.html">https://doc.rust-lang.org/book/ch03-02-data-types.html</a></li><li>the Rust book, ownership: <a href="https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html">https://doc.rust-lang.org/book/ch04-00-understanding-ownership.html</a></li><li>the Rust book, references and borrowing: <a href="https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html">https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html</a></li><li>the Rust book, slices: <a href="https://doc.rust-lang.org/book/ch04-03-slices.html">https://doc.rust-lang.org/book/ch04-03-slices.html</a></li><li>the Rust book, structs: <a href="https://doc.rust-lang.org/book/ch05-00-structs.html">https://doc.rust-lang.org/book/ch05-00-structs.html</a></li><li>the Rust book, enums and pattern matching: <a href="https://doc.rust-lang.org/book/ch06-00-enums.html">https://doc.rust-lang.org/book/ch06-00-enums.html</a></li><li>the Rust book, error handling with result: <a href="https://doc.rust-lang.org/book/ch09-00-error-handling.html">https://doc.rust-lang.org/book/ch09-00-error-handling.html</a></li><li>the Rust book, generics, traits, and lifetimes: <a href="https://doc.rust-lang.org/book/ch10-00-generics.html">https://doc.rust-lang.org/book/ch10-00-generics.html</a></li><li>Rust by example: <a href="https://doc.rust-lang.org/rust-by-example/">https://doc.rust-lang.org/rust-by-example/</a></li><li>the standard library docs: <a href="https://doc.rust-lang.org/std/">https://doc.rust-lang.org/std/</a></li><li>the cargo book: <a href="https://doc.rust-lang.org/cargo/">https://doc.rust-lang.org/cargo/</a></li><li>Rust compiler error index: <a href="https://doc.rust-lang.org/error_codes/error-index.html">https://doc.rust-lang.org/error_codes/error-index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832ee75a85a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 2: I Went Deep on LangChain Models. Here’s What You Actually Need to Know.]]></title>
            <link>https://medium.com/@anirudhmakhana/day-2-i-went-deep-on-langchain-models-heres-what-you-actually-need-to-know-109d5379c66d?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/109d5379c66d</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 06:58:56 GMT</pubDate>
            <atom:updated>2026-03-11T06:58:56.178Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part of the Zero to agent series — where I document learning Gen AI in public. </em><a href="https://medium.com/p/cfa4aeae69b0"><em>Day 1 is here</em></a><em> if you’re just joining.</em></p><p>Day 1 was the 10,000-foot view — six components, one mental model, no code. Today I went deep on just one of those components: <strong>Models</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgX6hdYg-NIc9ktl0_IbyA.png" /></figure><p>This might seem like the most boring place to start. It’s not. The model layer is the thing everything else plugs into, and there are some non-obvious distinctions here that’ll save you real confusion later.</p><p>Here’s everything I learned.</p><p>— — —</p><h3>What the Model Layer Actually Does</h3><p>LangChain’s model abstraction solves one problem: every AI provider has its own SDK, its own request format, its own quirks. Without an abstraction layer, switching from OpenAI to Claude means rewriting code. With LangChain, it’s one line.</p><p>But models in LangChain aren’t all the same type. There are two fundamentally different categories, and understanding the difference matters more than most tutorials let on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuy5mJlhP8sUaBlTUBBD_A.png" /></figure><p><strong>Language Models</strong> — take text in, return text out. Used for generation, summarization, code, translation, chat.</p><p><strong>Embedding Models</strong> — take text in, return a vector (a list of numbers) out. Used for semantic search and RAG. We’ll get to those at the end.</p><p>Inside Language Models, there’s another split that trips people up.</p><h3>LLMs vs Chat Models — Not the Same Thing</h3><p>This is the distinction I wish someone had explained clearly before I started.</p><p><strong>LLMs (Base Models)</strong> take a plain string as input and return a plain string. They’re trained on raw text — books, articles, web pages — and optimized for text completion. You give them a string, they continue it.</p><p><strong>Chat Models</strong> take a <em>list of messages</em> as input and return a <em>message object</em>. They’re fine-tuned on dialogue datasets and understand roles: system, user, assistant. These are the models behind ChatGPT, Claude, and Gemini.</p><p>Here’s the key thing: <strong>LLMs are largely obsolete for application development in 2025.</strong> Chat models are smarter, follow instructions better, and are what all modern providers optimize for. The only reason to know base LLMs exist is so you don’t get confused when you see them in older tutorials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uuTgojQDAqnkoriGYrDwA.png" /></figure><h3>Code: LLMs (Base Models)</h3><p>Rarely used, but useful to see the interface so you understand what changed.</p><pre># pip install langchain-openai python-dotenv<br>from langchain_openai import OpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()  # reads OPENAI_API_KEY from your .env file<br># gpt-3.5-turbo-instruct is one of the last remaining base LLMs from OpenAI<br>llm = OpenAI(model=&quot;gpt-3.5-turbo-instruct&quot;)<br>result = llm.invoke(&quot;What is the capital of India?&quot;)<br>print(result)  # returns a plain string</pre><p>Notice: .invoke() returns a raw string. No .content, no message object — just text.</p><h3>Code: Chat Models</h3><p>This is what you’ll actually use. The key differences: import paths are provider-specific, and .invoke() returns a message object, not a plain string. Access the text with .content.</p><h3>OpenAI</h3><pre># pip install langchain-openai<br>from langchain_openai import ChatOpenAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br># gpt-4.1-2025-04-14: OpenAI&#39;s current best model for coding + instruction following<br># 1M token context window, released April 2025<br>model = ChatOpenAI(<br>    model=&quot;gpt-4.1-2025-04-14&quot;,<br>    temperature=0.7,<br>)<br>result = model.invoke(&quot;Write a 5 line poem on cricket&quot;)<br>print(result.content)  # .content extracts the text from the AIMessage object</pre><h3>Anthropic (Claude)</h3><pre># pip install langchain-anthropic<br>from langchain_anthropic import ChatAnthropic<br>from dotenv import load_dotenv<br><br>load_dotenv()<br># claude-sonnet-4-5: Anthropic&#39;s current recommended model for most tasks<br>model = ChatAnthropic(model=&quot;claude-sonnet-4-5-20251001&quot;)<br>result = model.invoke(&quot;What is the capital of India?&quot;)<br>print(result.content)</pre><h3>Google Gemini</h3><pre># pip install langchain-google-genai<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from dotenv import load_dotenv<br><br>load_dotenv()<br># gemini-2.0-flash: Google&#39;s current fast, capable model<br>model = ChatGoogleGenerativeAI(model=&quot;gemini-2.0-flash&quot;)<br>result = model.invoke(&quot;What is the capital of India?&quot;)<br>print(result.content)</pre><h3>Understanding temperature</h3><p>temperature is a parameter you&#39;ll set on almost every model. It controls how random the output is — low values make the model more deterministic and consistent, high values make it more creative and varied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iuH8eQFNVvkCoFvkCIkVw.png" /></figure><pre># Precise and consistent — good for code generation<br>model = ChatOpenAI(model=&quot;gpt-4.1-2025-04-14&quot;, temperature=0.1)<br><br># More creative — good for writing tasks<br>model = ChatOpenAI(model=&quot;gpt-4.1-2025-04-14&quot;, temperature=0.9)</pre><p>A practical note: most providers cap temperature at 2.0. Going above 1.2 in production usually makes outputs unreliable — useful for brainstorming, not for anything user-facing.</p><h3>Open-Source Models</h3><p>Everything above is closed-source — you’re sending your queries to someone else’s servers and paying per token. Open-source models are an alternative: freely available, downloadable, and deployable wherever you want.</p><p>The main hub for finding them is <a href="https://huggingface.co/models">Hugging Face</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-wjTgyh-_ZEnF769JED9Jg.png" /></figure><h3>Notable open-source models worth knowing in 2025:</h3><ul><li><strong>Meta LLaMA 3.3</strong> — Meta’s current flagship open model, strong general performance</li><li><strong>Mistral 7B / Mixtral 8x7B</strong> — efficient, popular for self-hosted deployments</li><li><strong>Qwen 2.5</strong> — strong multilingual and coding performance</li><li><strong>Phi-3 Mini</strong> — Microsoft’s small model, surprisingly capable, runs on CPU</li></ul><h3>Two ways to use them in LangChain:</h3><p><strong>Option 1 — Hugging Face Inference API</strong> (easier, has a free tier, no GPU needed)</p><pre># pip install langchain-huggingface<br>from langchain_huggingface import HuggingFaceEndpoint<br>from dotenv import load_dotenv<br><br>load_dotenv()  # needs HF_TOKEN in .env<br><br>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;meta-llama/Meta-Llama-3.3-70B-Instruct&quot;,<br>    temperature=0.7,<br>)<br><br>result = llm.invoke(&quot;Explain transformers in simple terms&quot;)<br>print(result)</pre><p><strong>Option 2 — Run locally (full control, but needs a GPU for large models)</strong></p><pre># pip install langchain-huggingface transformers torch<br>from langchain_huggingface import HuggingFacePipeline<br><br># Phi-3 Mini is small enough to run on CPU — good for testing<br>llm = HuggingFacePipeline.from_model_id(<br>    model_id=&quot;microsoft/Phi-3-mini-4k-instruct&quot;,<br>    task=&quot;text-generation&quot;,<br>)<br><br>result = llm.invoke(&quot;What is machine learning?&quot;)<br>print(result)</pre><h3>The honest tradeoffs of open-source:</h3><p>Running your own model sounds great until you hit the practical reality. Large models (70B parameters and up) need expensive GPUs to run at reasonable speed. Setup requires installing PyTorch, CUDA drivers, and the right versions of everything — which is its own adventure. And most open-source models don’t have the RLHF fine-tuning that makes GPT-4 and Claude so good at following instructions precisely.</p><p>That said, for privacy-sensitive use cases or cost-sensitive production workloads, they’re worth the tradeoff. The HF Inference API removes most of the setup pain if you just want to experiment.</p><h3>Embedding Models</h3><p>Embedding models are completely different from language models. They don’t generate text. They convert text into a high-dimensional vector — a list of floating point numbers — that represents the <em>meaning</em> of the input.</p><p>Why does this matter? Because texts with similar meanings produce similar vectors. That’s the foundation of semantic search and RAG: instead of matching keywords, you’re matching meaning.</p><h4>Embed a single query</h4><pre># pip install langchain-openai<br>from langchain_openai import OpenAIEmbeddings<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>embedding = OpenAIEmbeddings(<br>    model=&quot;text-embedding-3-large&quot;,<br>    dimensions=512  # full model is 3072 dims; 512 is much faster with minimal quality loss<br>)<br><br>vector = embedding.embed_query(&quot;Delhi is the capital of India&quot;)<br>print(f&quot;Vector length: {len(vector)}&quot;)   # 512<br>print(vector[:4])                        # first 4 values — just floats</pre><h4>Embed multiple documents</h4><pre>embedding = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;, dimensions=512)<br><br>documents = [<br>    &quot;Delhi is the capital of India&quot;,<br>    &quot;Kolkata is the capital of West Bengal&quot;,<br>    &quot;Paris is the capital of France&quot;<br>]<br><br>vectors = embedding.embed_documents(documents)<br>print(f&quot;{len(vectors)} documents, each with {len(vectors[0])} dimensions&quot;)</pre><h4>Open-source embeddings with Hugging Face</h4><pre># pip install langchain-huggingface sentence-transformers<br>from langchain_huggingface import HuggingFaceEmbeddings<br><br>embedding = HuggingFaceEmbeddings(<br>    model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;<br>    # Free, runs locally, 384-dimensional vectors — great for prototyping<br>)<br><br>documents = [<br>    &quot;Delhi is the capital of India&quot;,<br>    &quot;Kolkata is the capital of West Bengal&quot;,<br>    &quot;Paris is the capital of France&quot;<br>]<br><br>vectors = embedding.embed_documents(documents)<br>print(f&quot;{len(vectors)} docs × {len(vectors[0])} dims&quot;)</pre><h3>Putting it together: semantic search</h3><p>This is the piece that clicked everything into place for me. Here’s a minimal end-to-end example: a small “knowledge base” of cricket player descriptions, and a query that finds the right one by meaning — not by keyword matching.</p><pre>from langchain_openai import OpenAIEmbeddings<br>from sklearn.metrics.pairwise import cosine_similarity<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>embedding = OpenAIEmbeddings(model=&quot;text-embedding-3-large&quot;, dimensions=512)<br><br># These are your &quot;documents&quot; — in a real app, these come from a PDF or database<br>documents = [<br>    &quot;Virat Kohli is an Indian cricketer known for his aggressive batting and leadership.&quot;,<br>    &quot;MS Dhoni is a former Indian captain famous for his calm demeanor and finishing skills.&quot;,<br>    &quot;Sachin Tendulkar, known as the &#39;God of Cricket&#39;, holds many batting records.&quot;,<br>    &quot;Rohit Sharma is known for his elegant batting and record-breaking double centuries.&quot;,<br>    &quot;Jasprit Bumrah is an Indian fast bowler known for his unorthodox action and yorkers.&quot;<br>]<br><br>query = &quot;tell me about bumrah&quot;<br><br># Embed everything<br>doc_embeddings = embedding.embed_documents(documents)<br>query_embedding = embedding.embed_query(query)<br><br># Find the most similar document using cosine similarity<br>scores = cosine_similarity([query_embedding], doc_embeddings)[0]<br>best_idx = scores.argmax()<br><br>print(f&quot;Query:      {query}&quot;)<br>print(f&quot;Best match: {documents[best_idx]}&quot;)<br>print(f&quot;Score:      {scores[best_idx]:.4f}&quot;)<br><br># Output: correctly returns the Bumrah document<br># even though the query shares no keywords with it</pre><p>The query “tell me about bumrah” and the Bumrah document don’t share a single keyword. But they land near each other in vector space because they’re <em>about</em> the same thing. That’s semantic search. And this toy example is exactly how RAG works at its core — you just swap the five cricket sentences for thousands of chunks from a real document.</p><h3>Installation Cheatsheet</h3><pre># Core<br>pip install langchain python-dotenv<br><br># Provider packages — install what you need<br>pip install langchain-openai          # GPT models + OpenAI embeddings<br>pip install langchain-anthropic       # Claude<br>pip install langchain-google-genai    # Gemini<br>pip install langchain-huggingface     # HuggingFace models + embeddings<br>pip install sentence-transformers     # Required for local HF embeddings<br><br># For the semantic search example<br>pip install scikit-learn numpy</pre><h3>What I Actually Took Away From Today</h3><p>A few things that genuinely shifted how I think about this:</p><p><strong>Chat models replaced LLMs and there’s no going back.</strong> The “LLM” term gets used loosely everywhere, but in LangChain there’s an actual distinction. In practice, you’ll only use ChatOpenAI, ChatAnthropic, etc. — not the base OpenAI class.</p><p><strong>The import paths matter.</strong> The old from langchain.chat_models import ... is deprecated. Provider-specific packages (langchain_openai, langchain_anthropic) are the right way now. Half the tutorials you&#39;ll find online still show the old way.</p><p><strong>Embeddings aren’t generation.</strong> They’re lookup. The mental model that helped me: language models answer questions, embedding models file things so you can find them later.</p><p><strong>The semantic search example is RAG in miniature.</strong> Five documents, one query, cosine similarity. Scale that to thousands of chunks from a real PDF and add an LLM to synthesize the results — that’s the full RAG pattern. We’ll build it properly when we get to indexes.</p><h4>Sources and links:</h4><ul><li>“ChatOpenAI” → <a href="https://python.langchain.com/api_reference/openai/chat_models/langchain_openai.chat_models.base.ChatOpenAI.html">https://python.langchain.com/api_reference/openai/chat_models/langchain_openai.chat_models.base.ChatOpenAI.html</a></li><li>“ChatAnthropic” → <a href="https://python.langchain.com/api_reference/anthropic/chat_models/langchain_anthropic.chat_models.ChatAnthropic.html">https://python.langchain.com/api_reference/anthropic/chat_models/langchain_anthropic.chat_models.ChatAnthropic.html</a></li><li>“ChatGoogleGenerativeAI” → <a href="https://python.langchain.com/api_reference/google_genai/chat_models/langchain_google_genai.chat_models.ChatGoogleGenerativeAI.html">https://python.langchain.com/api_reference/google_genai/chat_models/langchain_google_genai.chat_models.ChatGoogleGenerativeAI.html</a></li></ul><p><strong>Open-source section</strong></p><ul><li>“Hugging Face” → <a href="https://huggingface.co/models?pipeline_tag=text-generation&amp;sort=trending">https://huggingface.co/models?pipeline_tag=text-generation&amp;sort=trending</a></li><li>“HuggingFaceEndpoint” → <a href="https://python.langchain.com/api_reference/huggingface/llms/langchain_huggingface.llms.huggingface_endpoint.HuggingFaceEndpoint.html">https://python.langchain.com/api_reference/huggingface/llms/langchain_huggingface.llms.huggingface_endpoint.HuggingFaceEndpoint.html</a></li></ul><p><strong>Embeddings section</strong></p><ul><li>“OpenAIEmbeddings” → <a href="https://python.langchain.com/api_reference/openai/embeddings/langchain_openai.embeddings.base.OpenAIEmbeddings.html">https://python.langchain.com/api_reference/openai/embeddings/langchain_openai.embeddings.base.OpenAIEmbeddings.html</a></li><li>“HuggingFaceEmbeddings” → <a href="https://python.langchain.com/api_reference/huggingface/embeddings/langchain_huggingface.embeddings.huggingface.HuggingFaceEmbeddings.html">https://python.langchain.com/api_reference/huggingface/embeddings/langchain_huggingface.embeddings.huggingface.HuggingFaceEmbeddings.html</a></li><li>“sentence-transformers/all-MiniLM-L6-v2” → <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2</a></li></ul><p><strong>Model provider docs</strong> (add at the end of each provider’s code block as a “→ Docs:” line):</p><ul><li>OpenAI models list → <a href="https://platform.openai.com/docs/models">https://platform.openai.com/docs/models</a></li><li>Anthropic models list → <a href="https://docs.anthropic.com/en/docs/about-claude/models/overview">https://docs.anthropic.com/en/docs/about-claude/models/overview</a></li><li>Google Gemini models → <a href="https://ai.google.dev/gemini-api/docs/models">https://ai.google.dev/gemini-api/docs/models</a></li></ul><p><em>Zero to Agent is a series where I learn Gen AI in public and document everything. If you’re on the same journey, follow along — </em><a href="https://medium.com/p/cfa4aeae69b0"><em>Day 1 is here</em></a><em>.</em></p><p><em>If something here is wrong or unclear, drop a comment. Learning in public means being wrong in public too.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=109d5379c66d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Started Learning LangChain. Here’s Everything That Actually Made Sense on Day 1.]]></title>
            <link>https://medium.com/@anirudhmakhana/i-started-learning-langchain-heres-everything-that-actually-made-sense-on-day-1-cfa4aeae69b0?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa4aeae69b0</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 10:59:11 GMT</pubDate>
            <atom:updated>2026-03-09T10:59:11.944Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is part of an ongoing series where I document learning Gen AI in public-what I understood, what confused me, and what I built along the way. I’m a backend engineer picking this up from scratch, writing for developers in the same boat.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45hO2JOztoSqjLhNRf8YZg.png" /></figure><p>I’ve been building on top of blockchain infrastructure for the past few years. Stateless APIs, distributed systems, cross-chain plumbing — that’s my world. But recently I kept running into a wall: every time I wanted to add something AI-powered to a project, I found myself stitching together raw API calls, fighting provider-specific quirks, and reinventing the same patterns over and over.</p><p>So I decided to go back to basics and actually learn LangChain properly.</p><p>Day 1 was about fundamentals. No project yet, just getting a clear mental model of what LangChain actually is and what problem each of its core components solves.</p><p>Here’s what I learned.</p><p>— — —</p><h3>What is LangChain, and why does it exist?</h3><p><a href="https://www.langchain.com/">LangChain</a> is a framework for building applications powered by large language models. But that description undersells it.</p><p>The real problem it solves is this: building with LLMs without a framework feels like building a web server without Express. You <em>can</em> do it, but you end up writing a lot of boilerplate, and every provider (OpenAI, Anthropic, Google) has a slightly different interface that forces you to rewrite the same logic whenever you switch.</p><p>LangChain gives you a standard set of abstractions so you can focus on what you’re building, not on provider-specific plumbing.</p><p>It has six core components. Each one solves a specific problem.</p><h3>1. Models — One Interface to Rule Them All</h3><p>The first problem LangChain addresses is provider fragmentation. OpenAI, Anthropic, Cohere, Mistral — they all have different SDKs, different request shapes, different response formats.</p><p>LangChain wraps them all in a unified interface. Switching from GPT-4 to Claude is literally a one-line change:</p><pre>from langchain.chat_models import ChatOpenAI<br>from langchain.chat_models import ChatAnthropic<br><br>llm = ChatOpenAI(model=&quot;gpt-4&quot;)        # OpenAI<br>llm = ChatAnthropic(model=&quot;claude-3&quot;)  # Claude — same interface</pre><p>Everything downstream — your chains, your agents, your memory — works the same regardless of which model is underneath.</p><p>LangChain also distinguishes between two types of models:</p><p><strong>Language models</strong> take text in and return text out. These are your GPT-4s and Claudes — used for chat, summarization, code generation, anything conversational.</p><p><strong>Embedding models</strong> take text in and return a vector (a list of numbers) out. These are used for semantic search and similarity — powering things like “find me documents related to this query.” We’ll come back to these when we get to indexes.</p><h3>2. Prompts — Stop Hardcoding Strings</h3><p>Before LangChain, my prompts were hardcoded strings scattered across my codebase. They worked, but they weren’t reusable, they weren’t testable, and the moment I needed to change something I had to hunt through the code.</p><p>LangChain introduces <strong>Prompt Templates</strong> — parameterized prompts that you can reuse with different inputs:</p><pre>from langchain.prompts import PromptTemplate<br><br>template = PromptTemplate(<br>    input_variables=[&quot;topic&quot;, &quot;audience&quot;],<br>    template=&quot;Explain {topic} to someone who is {audience}. Be concise.&quot;<br>)<br><br>prompt = template.format(topic=&quot;embeddings&quot;, audience=&quot;a backend engineer&quot;)</pre><p>For chat models specifically, you also get <strong>role-based prompts</strong> where you structure messages by role — system, human, AI — which maps directly to how chat APIs actually work:</p><pre>from langchain.prompts import ChatPromptTemplate<br><br>prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, &quot;You are a concise technical writer.&quot;),<br>    (&quot;human&quot;, &quot;Explain {topic} in under 100 words.&quot;)<br>])</pre><p>There’s also <strong>few-shot prompting</strong> — a technique where you include example input/output pairs in your prompt to show the model what you want, rather than just telling it. This is particularly powerful when you need consistent formatting or a specific style of response.</p><p>The key insight here: prompts are not afterthoughts. They’re first-class components of your application. Treating them that way makes your codebase a lot cleaner.</p><h3>3. Chains — Building Pipelines</h3><p>A chain is exactly what it sounds like: a sequence of steps where the output of one feeds into the next.</p><p>The simplest chain is just a prompt template connected to an LLM:</p><pre>Prompt Template → LLM → Output</pre><p>But chains get interesting when you stack them. Say you want to take English text, translate it to Hindi, and then summarize it to under 100 words. That’s two LLM calls chained together:</p><pre>English input → [Chain 1: Translate to Hindi] → [Chain 2: Summarize] → Final output</pre><p>LangChain has several chain types worth knowing:</p><ul><li><strong>LLMChain</strong> — the basic building block, single prompt to single LLM call</li><li><strong>SequentialChain</strong> — runs chains one after another, output of chain A becomes input of chain B</li><li><strong>RouterChain</strong> — inspects the input and routes it to different chains based on what it is</li><li><strong>ParallelChain</strong> — runs multiple chains simultaneously and combines the results</li></ul><p>The mental model I found useful: chains are for workflows where <em>you</em> know the steps in advance. You’re defining the pipeline explicitly. This works great for most applications — summarization, translation, classification, document Q&amp;A.</p><p>When you don’t know the steps in advance, that’s when you need agents. We’ll get there.</p><h3>4. Memory — Giving LLMs a Short-Term Brain</h3><p>Here’s something that surprised me when I first started working with LLM APIs: they’re completely stateless.</p><p>Every API call is independent. Send a message, get a response, send another message — the model has no idea what you said before. If you’re building a chatbot, you have to manually include the conversation history in every single request.</p><p>LangChain’s memory components handle this for you. But there’s a tradeoff: more history means more tokens, which means higher cost and eventually hitting context limits. Different memory types handle this tradeoff differently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S51LoVWhdi0OeOJuUAJLbg.png" /></figure><pre>from langchain.memory import ConversationBufferWindowMemory<br><br>memory = ConversationBufferWindowMemory(k=5)  # only remember last 5 exchanges</pre><p>My rule of thumb: start with BufferWindowMemory with a reasonable k. If conversations go long and you need context from early in the chat, move to SummaryMemory.</p><h3>5. Indexes — Connecting LLMs to Your Data</h3><p>This one is the most powerful concept I learned today, and it’s the foundation of a pattern called <strong>RAG (Retrieval-Augmented Generation)</strong>.</p><p>The problem: LLMs are trained on public data up to a cutoff date. They know nothing about your internal documents, your product, your database, your PDFs. How do you make an LLM answer questions about data it has never seen?</p><p>The answer is not fine-tuning (expensive, slow, requires retraining every time data changes). The answer is retrieval.</p><p>Here’s the pipeline:</p><pre>1. Load your documents (PDFs, websites, CSVs, databases)<br>2. Split them into smaller chunks<br>3. Convert each chunk into an embedding (a vector)<br>4. Store those vectors in a vector database<br>5. At query time: embed the user&#39;s question, find the most similar chunks, pass them to the LLM as context</pre><p>The LLM then answers based on the retrieved context — not from memory, but from your actual data.</p><p>LangChain breaks this into four component types:</p><p><strong>Document Loaders</strong> — read your raw content. There are loaders for PDFs, web pages, CSVs, Notion, Google Drive, YouTube transcripts, and more.</p><p><strong>Text Splitters</strong> — chunk the content into pieces the model can handle. You control chunk size and overlap.</p><p><strong>Embedding Models</strong> — convert each chunk into a vector using a model like OpenAI’s text-embedding-ada-002.</p><p><strong>Vector Stores</strong> — databases optimized for storing and searching vectors. Popular options: Pinecone (managed), Chroma (local), FAISS (in-memory).</p><pre>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain.vectorstores import Chroma<br><br># Load → Split → Embed → Store<br>docs = PyPDFLoader(&quot;report.pdf&quot;).load()<br>chunks = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50).split_documents(docs)<br>vectorstore = Chroma.from_documents(chunks, OpenAIEmbeddings())<br># Query<br>retriever = vectorstore.as_retriever()<br>relevant_chunks = retriever.get_relevant_documents(&quot;What was the Q3 revenue?&quot;)</pre><p>This unlocks a whole category of applications: document Q&amp;A, internal knowledge bases, customer support bots with real product knowledge, code search. Basically anything where you need an LLM to reason over data it wasn’t trained on.</p><h3>6. Agents — Let the Model Decide</h3><p>Agents are where LangChain gets genuinely interesting.</p><p>Everything so far — chains, memory, indexes — follows a flow <em>you</em> define. The developer decides the steps. The model just executes them.</p><p>Agents flip this. You give the model a set of <strong>tools</strong> (functions it can call) and a task, and the model decides which tools to use, in what order, based on what it observes. It loops until it reaches a final answer.</p><p>The pattern is called <strong>ReAct</strong> (Reason + Act): the model alternates between reasoning about the problem and taking an action (calling a tool), then observing the result, then reasoning again.</p><pre>from langchain.agents import initialize_agent, Tool<br>from langchain.tools import DuckDuckGoSearchRun<br><br>search = DuckDuckGoSearchRun()<br><br>tools = [<br>    Tool(<br>        name=&quot;WebSearch&quot;,<br>        func=search.run,<br>        description=&quot;Search the web for current information&quot;<br>    )<br>]<br><br>agent = initialize_agent(tools, llm, agent=&quot;zero-shot-react-description&quot;, verbose=True)<br>agent.run(&quot;What are the top LangChain alternatives in 2024 and how do they compare?&quot;)</pre><p>With verbose=True you can actually watch the model reason: &quot;I need to search for this... the result says X... now I should look up Y...&quot; It&#39;s genuinely impressive once you see it.</p><p>The key distinction from chains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAggSQFIziY8jVpqOO1RCw.png" /></figure><p>Use chains when you know exactly what needs to happen. Use agents when the task is complex enough that you’d need to think through it yourself before knowing the steps.</p><h3>The Mental Model</h3><p>Here’s how these six components relate to each other:</p><pre>User query<br>    ↓<br>[ Prompt ] — structures what you send to the model<br>    ↓<br>[ Model ] — unified interface to any LLM provider<br>    ↓<br>[ Chain ] — pipeline of steps to process and transform<br>    ↑<br>[ Memory ] — injects conversation history into the chain<br>    ↑<br>[ Index ] — injects external knowledge into the chain<br>    ↑<br>[ Agent ] — replaces the chain when the model needs to decide the steps</pre><p>Each component solves one specific problem. Together they cover pretty much everything you’d need to build a production LLM application.</p><h3>What’s Next</h3><p>This was day 1 — fundamentals only. Next I’m going deeper on each component individually, writing code for each one, and eventually building a real project that uses all of them together.</p><p>I’ll document everything here as I go. If you’re picking up LangChain or Gen AI at the same time, follow along — we’re figuring this out together.</p><p><em>If something here was unclear or wrong, I’d genuinely want to know — drop a comment. I’m learning in public, which means being wrong in public too.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa4aeae69b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before You Build With AI, You Should Probably Understand What It’s Doing]]></title>
            <link>https://medium.com/@anirudhmakhana/before-you-build-with-ai-you-should-probably-understand-what-its-doing-37c359c6d4bd?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c359c6d4bd</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 13:38:02 GMT</pubDate>
            <atom:updated>2026-02-27T13:38:02.905Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A builder’s guide to transformers — the math, the intuition, and why it actually matters when you’re shipping things on top of it.</em></p><figure><img alt="sad cat trying to understand maths about to give up" src="https://cdn-images-1.medium.com/max/736/1*U7EJWFemQcl2j-48jEL0Og.jpeg" /></figure><p>There’s a moment every builder hits when they’re working with AI.</p><p>You’re wiring up an LLM API. The responses are good. The product is coming together. And then something breaks, or behaves weirdly, or doesn’t do what you expected — and you realise you have no mental model for <em>why</em>. You’ve been treating it like a black box. A magic endpoint. You send text in, text comes out, ship it.</p><p>That moment hit me while building an AI-powered application. I’d been moving fast — RAG pipelines, prompt engineering, chaining calls together — and it was working. But I couldn’t reason about <em>why</em> it worked, or why it occasionally didn’t. I didn’t understand the foundation I was building on.</p><p>So I stopped and went all the way down to the math.</p><p>This is what I found. It’s a story, not a textbook — but I’m not going to water down the equations, because the equations are actually the interesting part.</p><h3>The One-Sentence Summary of Everything</h3><p>A large language model has one job:</p><p>Given a sequence of tokens, predict the probability distribution over what token comes next.</p><p>That’s it. Everything answering questions, writing code, reasoning through problems, passing bar exams is an emergent property of doing this one thing at incomprehensible scale.</p><p>When you call an LLM API, here’s what’s literally happening: your text gets converted into numbers, those numbers pass through a sequence of matrix multiplications, and the output is a probability distribution over every possible next word. The model samples one. Appends it. Runs again. That’s text generation — one token at a time, each token its own full model pass.</p><pre>input:  [&#39;The&#39;, &#39;cat&#39;, &#39;sat&#39;, &#39;on&#39;, &#39;the&#39;]<br><br>output: P(&#39;mat&#39;)   = 0.34<br>        P(&#39;floor&#39;) = 0.18<br>        P(&#39;roof&#39;)  = 0.09<br>        P(&#39;dog&#39;)   = 0.001<br>        ... (probability for all 50,257 tokens in the vocabulary)</pre><p>Simple. Almost embarrassingly simple. And yet the capabilities that emerge from doing this at scale are genuinely hard to explain.</p><p>Understanding <em>why</em> is worth your time as a builder and not to implement your own model, but because the architecture shapes the constraints, and the constraints shape what you can build.</p><h3>Three Math Primitives</h3><p>Before attention makes sense, three mathematical ideas need to be in your head. These are the atoms everything else is built from.</p><h4>1. Vectors: numbers with direction</h4><p>A vector is a list of numbers. [1.2, -0.7, 3.4] is a 3-dimensional vector. GPT-3 works with vectors that have 12,288 numbers. Every token — every word, every punctuation mark — becomes one of these high-dimensional arrows.</p><p>The key insight is that after training, these vectors <em>encode meaning</em>. Similar concepts end up geometrically close in this 12,288-dimensional space. This isn’t programmed. It emerges.</p><h4>2. The Dot Product: measuring similarity</h4><p>Multiply corresponding components of two vectors and sum the results:</p><pre>a = [1, 2, 3]<br>b = [4, 5, 6]</pre><pre>a · b = (1×4) + (2×5) + (3×6) = 4 + 10 + 18 = 32</pre><p>The geometric interpretation: <strong>a large positive dot product means the vectors point in the same direction — they’re similar.</strong> Zero means unrelated. Negative means opposite. This single operation is how the model measures relevance between tokens. High dot product = “these two things are related.”</p><h4>3. Matrix Multiplication: the engine</h4><p>A matrix is a 2D grid of numbers. Multiplying a matrix by a vector transforms it into a new vector. Every single layer of a transformer is fundamentally: take a vector, multiply by a matrix of learned weights, get a new vector that’s more useful for predicting the next token.</p><pre>output = W × input</pre><pre>W contains learned numbers — adjusted by training across trillions of examples<br>until the transformations it applies become useful for next-token prediction</pre><p>Backpropagation — the training algorithm — nudges every number in every matrix across trillions of examples until the whole machine gets good at autocomplete. GPT-3 has approximately 28,000 matrices and 175 billion individual numbers. They all start random. After training, they encode the patterns of essentially all human text ever written.</p><h3>Step One: Text Becomes Numbers</h3><p>The model doesn’t read. It processes integers.</p><p>Before any math happens, text gets converted into <strong>tokens</strong> — chunks of text mapped to integer IDs. Tokens aren’t words. They’re subword pieces, optimised by an algorithm called Byte Pair Encoding (BPE).</p><pre>&#39;unbelievable&#39; → [&#39;un&#39;, &#39;believ&#39;, &#39;able&#39;]        (3 tokens)<br>&#39;ChatGPT&#39;      → [&#39;Chat&#39;, &#39;G&#39;, &#39;PT&#39;]              (3 tokens)<br>&#39;the&#39;          → [&#39;the&#39;]                           (1 token)</pre><p>GPT-3 has a vocabulary of 50,257 tokens. Rough rule: 1 token ≈ 4 characters ≈ 0.75 English words. When a model advertises a “128k context window,” that’s 128,000 of these token units — not 128,000 words. This matters when you’re thinking about cost and chunking strategies.</p><p>BPE builds the vocabulary by starting with individual characters and repeatedly merging the most frequent adjacent pair until the target vocabulary size is hit. Common words become single tokens. Rare or domain-specific words get split into pieces. The model can handle any input — even words it never saw during training — by decomposing them into known subword components.</p><h3>Step Two: Tokens Become Vectors</h3><p>Token IDs are just integers. The integer 4914 (the ID for &#39;king&#39;) has no mathematical relationship to 16599 (the ID for &#39;queen&#39;). We need a representation where similar meanings live close together.</p><p>That’s the <strong>embedding matrix</strong> — a giant lookup table.</p><pre>W_E shape: [12,288 × 50,257]   (GPT-3)</pre><pre>To embed token i:<br>  E_i = W_E[:, i]   ← grab the i-th column</pre><pre>Result: a vector of 12,288 numbers representing that token<br>Parameters: 12,288 × 50,257 = 617,558,016</pre><p>After training, these vectors develop geometric structure nobody explicitly programmed:</p><pre>king - man + woman ≈ queen<br>actor - man + woman ≈ actress<br>Paris - France + Germany ≈ Berlin</pre><p>The model discovered that organising vectors with consistent ‘gender’ and ‘geography’ directions made next-token prediction easier. So it learned to do it.</p><p>There’s one more piece: <strong>positional encodings.</strong> Unlike RNNs, transformers process all tokens simultaneously — there’s no inherent notion of order. Token 1 and Token 1,000 look identical to the model without extra information. So before feeding tokens into the transformer, a position-specific vector is added to each token embedding:</p><pre>final_embedding(token_i) = embed(token_i) + positional_encoding(i)</pre><pre>positional encodings in GPT-3:<br>  shape: [2,048 × 12,288]   (one learned vector per position)<br>  parameters: 25,165,824</pre><p>After this step, the input to the transformer is a matrix of shape [n_tokens × 12,288]. Each row is one token&#39;s vector. The transformer&#39;s job is to enrich these vectors through 96 layers of operations - until the final vector in the sequence can predict what comes next.</p><h3>A Necessary Detour: Softmax</h3><p>Softmax appears in two places in every transformer: converting raw scores into attention weights inside the model, and converting logits to a next-token probability distribution at the output. Understanding it is non-negotiable.</p><p><strong>The problem:</strong> matrix multiplications produce raw numbers (logits) that can be anything — negative, greater than 1, wildly large. To use them as probabilities, every value must be between 0 and 1, and all values must sum to exactly 1.</p><p><strong>The formula:</strong></p><pre>softmax(z)_i = e^(z_i) / Σ_j e^(z_j)</pre><p>You exponentiate every number, then divide each by the sum of all of them. Step by step:</p><pre>logits = [2.0, 1.0, 0.5, -1.0]</pre><pre>Step 1 - exponentiate each value:<br>  e^2.0  = 7.389<br>  e^1.0  = 2.718<br>  e^0.5  = 1.649<br>  e^-1.0 = 0.368</pre><pre>Step 2 - sum: 12.124</pre><pre>Step 3 - divide each by the sum:<br>  7.389 / 12.124 = 0.609   (61%)<br>  2.718 / 12.124 = 0.224   (22%)<br>  1.649 / 12.124 = 0.136   (14%)<br>  0.368 / 12.124 = 0.030   ( 3%)</pre><pre>Result: [0.609, 0.224, 0.136, 0.030]<br>  ✓ all between 0 and 1<br>  ✓ sum = 1.0</pre><p>The exponential function amplifies differences — high scores get disproportionately more weight, low scores get crushed toward zero. This creates sharp, decisive distributions rather than flat ones.</p><p><strong>Temperature</strong> is a scalar you divide logits by before softmax — a real lever, not a magic knob:</p><pre>softmax(z / T)</pre><pre>T = 0.5  → sharper distribution, model commits harder to top choice<br>T = 1.0  → default<br>T = 2.0  → flatter distribution, more &quot;creative&quot; (read: random)<br>T → 0    → always picks the single highest-probability token<br>T → ∞   → uniform distribution, every token equally likely</pre><p>When you’re tuning temperature in your application, you’re literally adjusting a divisor applied to logits before this formula runs. Now you know why it behaves the way it does.</p><h3>The Big One: Attention</h3><p>Everything above was setup.</p><p>This is the mechanism that changed everything — published in 2017 in <em>“Attention Is All You Need”</em> by Vaswani et al. at Google. Arguably the most consequential ML paper of the last decade.</p><p><strong>The problem attention solves:</strong></p><p>After embedding, every token has a vector — but it’s context-free. The word “mole” gets the same initial vector regardless of whether the sentence is about the animal, the chemistry unit, or the skin condition. Attention’s job is to update each token’s vector based on surrounding context, so by the time vectors reach the output, they encode the correct context-specific meaning.</p><p><strong>Queries, Keys, and Values</strong></p><p>Think of attention as a fuzzy search engine built inside the model, running on every token simultaneously. Each attention head learns three weight matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*41lBPn74GFLqF_Gq9obAgg.png" /></figure><p>For each token embedding E_i:</p><pre>Q_i = W_Q × E_i    (what is this token searching for?)<br>K_i = W_K × E_i    (what does this token contain?)<br>V_i = W_V × E_i    (what information can this token contribute?)</pre><p>In GPT-3, W_Q and W_K compress vectors from 12,288 dimensions down to 128. The value transformation passes through the same bottleneck — splitting one large matrix into two smaller ones (W_V↓ and W_V↑). This “low-rank factorisation” cuts ~150 million parameters per head down to ~3 million. Same expressiveness, 50x fewer weights.</p><p><strong>Computing attention scores</strong></p><p>To find how relevant token j is to updating token i — dot product their query and key vectors:</p><pre>score(i, j) = Q_i · K_j</pre><p>Large positive score = “token j is highly relevant to token i.” We compute this for every pair in the sequence, producing an n × n matrix of scores. For GPT-3 with a 2,048-token context: a 2,048 × 2,048 grid — roughly 4 million numbers per head.</p><p>This is why scaling context windows is expensive. <strong>Doubling context length quadruples the attention computation.</strong> The quadratic relationship between context length and compute is a fundamental architectural constraint — knowing this helps you reason about when RAG makes sense versus stuffing everything into context.</p><p><strong>Scaling by √dk</strong></p><p>Before softmax, divide all scores by the square root of the key dimension:</p><pre>scaled_score(i, j) = (Q_i · K_j) / √dk</pre><pre>GPT-3: dk = 128  →  √dk ≈ 11.31</pre><p>With 128-dimensional vectors, dot products can become large purely by chance. Large softmax inputs cause gradient saturation — training slows down or stops. Dividing by √128 keeps everything in a healthy range.</p><p><strong>Masking</strong></p><p>During training, the model processes the full sequence at once, predicting the next token for every position simultaneously. But token 5 cannot be allowed to look at token 6 — that would be cheating. So all future positions are masked before softmax:</p><pre>for all j &gt; i:  score(i, j) = -∞</pre><pre>After softmax:  e^(-∞) = 0  →  zero attention weight</pre><p>The model is structurally prevented from seeing the future.</p><p><strong>The full attention formula</strong></p><pre>Attention(Q, K, V) = softmax( mask( QK^T / √dk ) ) V</pre><p>Step by step through a real example — the sentence <em>“a fluffy blue creature roamed the forest”</em>:</p><p>The word “creature” generates a query vector asking roughly: “are there descriptors nearby?” The words “fluffy” and “blue” produce key vectors that score high against this query. After scaling and softmax:</p><pre>attention weights for updating &quot;creature&quot;:<br>  fluffy  → 0.58<br>  blue    → 0.42<br>  a       → 0.00<br>  roamed  → 0.00<br>  forest  → 0.00</pre><p>The update vector:</p><pre>ΔE_creature = 0.58 × V_fluffy + 0.42 × V_blue</pre><pre>E&#39;_creature = E_creature + ΔE_creature</pre><pre>before: generic animal vector<br>after:  fluffy blue creature vector</pre><p>One attention head. One pass. Context has been incorporated.</p><p><strong>Multi-head attention: 96 simultaneous lenses</strong></p><p>One head learns one type of contextual relationship. Language has many simultaneously — grammatical agreement, coreference (“it” → “the animal”), topic, sentiment, temporal order. GPT-3 runs 96 attention heads in parallel inside each block. Each has independent W_Q, W_K, W_V matrices, each discovering different patterns:</p><ul><li>some heads learn adjective → noun relationships</li><li>some learn pronoun → antecedent</li><li>some learn subject → verb</li><li>some learn named entities → context</li></ul><p>Nobody decides which head learns what. The model figures out what’s useful, guided only by the training signal.</p><p>All 96 heads’ updates are summed and added to the original embeddings. Then it happens again in the next layer. GPT-3 does this <strong>96 times</strong>.</p><p><strong>The parameter count, just to ground the scale:</strong></p><pre>Per head:  4 matrices × (12,288 × 128) ≈ 6.3M parameters<br>× 96 heads per layer                   ≈ 604M per layer<br>× 96 layers                            ≈ 58 billion parameters</pre><pre>That&#39;s 58 billion - just for attention.<br>The other ~117 billion live in MLP layers and embedding matrices.</pre><h3>One Complete Forward Pass</h3><p>Everything that happens when you call an LLM and get one token back:</p><pre>1. Tokenize<br>   &quot;The cat sat on the&quot; → [464, 3797, 3332, 319, 262]</pre><pre>2. Embed + add positional encoding<br>   5 IDs → 5 vectors of 12,288 numbers<br>   shape: [5 × 12,288]</pre><pre>3. For each of 96 transformer layers:<br>   a. Multi-head attention (96 heads in parallel):<br>      - Compute Q, K, V for all tokens<br>      - Score every pair: QK^T / √128<br>      - Mask future positions → -∞<br>      - Softmax → attention pattern<br>      - Weighted sum of V → updates ΔE<br>      - Sum all 96 heads&#39; updates into embeddings<br>   b. Layer norm<br>   c. Feed-forward MLP (per-token, independently):<br>      - Expand: 12,288 → 49,152<br>      - GELU nonlinearity<br>      - Compress: 49,152 → 12,288<br>   d. Layer norm</pre><pre>4. Take the last token&#39;s vector [12,288 numbers]<br>   Multiply by unembedding matrix W_U [50,257 × 12,288]<br>   → logits [50,257 numbers]</pre><pre>5. softmax(logits) → probability distribution over vocab</pre><pre>6. Sample one token → &quot;mat&quot;</pre><pre>7. Append to input. Go to step 1.</pre><p>Every matrix multiplication, every attention computation — parallelisable across thousands of GPU cores. This is why transformers won. Not necessarily cleverer math than predecessors — but math that scales. RNNs processed one token at a time sequentially; you had to wait for token 1 before computing token 2. Transformers removed that bottleneck entirely.</p><h3>The Part Nobody Can Fully Explain</h3><p>Nobody programmed grammar into GPT-3. Nobody told it what “Harry Potter” means. Nobody defined coreference resolution, or analogical reasoning, or the ability to write in different tones.</p><p>All of it emerged from one training objective: <em>predict the next token, on trillions of examples.</em></p><p>To do that well, the model had to internally build representations of syntax, world knowledge, reasoning patterns, style, cultural context — essentially everything humans encode in language. It discovered all of this because knowing all of this makes next-token prediction easier.</p><p>This is the central mystery of large language models. The training objective is almost insultingly simple. The emergent capabilities are staggeringly complex. An entire field of interpretability research exists because we genuinely don’t fully understand how capabilities arise from these operations.</p><p>We built something and don’t completely understand what we built. That’s both the most unsettling and the most exciting thing about working in this space right now.</p><h3>Why This Matters When You’re Building</h3><p>Here’s what shifted for me after going through all of this:</p><p><strong>Context windows are expensive for a specific reason.</strong> The n × n attention matrix means doubling context quadruples compute. This is why RAG exists. This is why long-context models are expensive. Now you can reason about the architectural tradeoff, not just the price tag.</p><p><strong>Temperature is a literal arithmetic operation.</strong> It’s a divisor applied to logits before softmax. When responses feel “too random” or “too rigid,” you’re observing the shape of a probability distribution being adjusted. Knowing this makes you a better debugger.</p><p><strong>Tokens ≠ words.</strong> 128k context window ≠ 128k words. Every time you’re reasoning about costs, chunking strategies, or context limits — think in tokens, not words.</p><p><strong>The model has no state between calls.</strong> Every forward pass starts fresh from the embedding matrix. “Memory” in AI applications is just injecting past context back into the input on each call. Understanding this makes you a better architect of stateful AI systems.</p><p><strong>Emergent capabilities are real and hard to predict.</strong> Nobody expected GPT-2 to do few-shot learning. Nobody predicted the reasoning capabilities that appeared in GPT-4. Staying close to the fundamentals — not just the product surface — is how you anticipate what’s coming rather than react to it.</p><h3>What’s Next</h3><p>This is the foundation. The next layer is understanding how models are fine-tuned and aligned (RLHF), how retrieval-augmented generation works at the infrastructure level, and how agentic workflows chain model calls together into something that can reason across multiple steps.</p><p>All of that is more interesting once you know what a single forward pass actually does.</p><p>If you’re building with AI and you’ve been treating it as a black box — I’d encourage you to take a weekend and go through the fundamentals. It’s not as deep as it looks from the outside, and the understanding compounds when you get back to building.</p><h3>Sources</h3><ul><li>Vaswani et al. (2017), <em>“Attention Is All You Need”</em> — <a href="https://arxiv.org/abs/1706.03762">arxiv.org/abs/1706.03762</a></li><li>Brown et al. (2020), <em>“Language Models are Few-Shot Learners”</em> (GPT-3 paper) — <a href="https://arxiv.org/abs/2005.14165">arxiv.org/abs/2005.14165</a></li><li>Ouyang et al. (2022), <em>“Training language models to follow instructions with human feedback”</em> (RLHF) — <a href="https://arxiv.org/abs/2203.02155">arxiv.org/abs/2203.02155</a></li><li>3Blue1Brown, <em>“But what is a GPT?”</em> — <a href="https://www.youtube.com/watch?v=wjZofJX0v4M">youtube.com/watch?v=wjZofJX0v4M</a></li><li>3Blue1Brown, <em>“Attention in transformers, visually explained”</em> — <a href="https://www.youtube.com/watch?v=eMlx5fFNoYc">youtube.com/watch?v=eMlx5fFNoYc</a></li><li>Andrej Karpathy, <em>“Let’s build GPT from scratch”</em> — <a href="https://www.youtube.com/watch?v=kCc8FmEb1nY">youtube.com/watch?v=kCc8FmEb1nY</a></li><li>Jay Alammar, <em>“The Illustrated Transformer”</em> — <a href="http://jalammar.github.io/illustrated-transformer/">jalammar.github.io/illustrated-transformer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c359c6d4bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating the Gelato Network with Pyth using Web3 Functions]]></title>
            <link>https://medium.com/@anirudhmakhana/integrating-the-gelato-network-with-pyth-using-web3-functions-760cc96126ba?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/760cc96126ba</guid>
            <category><![CDATA[hard-hat]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[web3function]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[gelatonetwork]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 08:22:10 GMT</pubDate>
            <atom:updated>2023-09-01T08:23:22.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In an era where the landscape of technology is being reshaped by decentralization, Gelato Network stands out as the world’s first decentralized backend service. It’s not just another addition to the growing roster of DeFi tools; it’s a paradigm shift offering automation for all applications on the blockchain. Today, we’ll delve into how this revolutionary system can be combined with the precision of the Pyth Network using Web3 Functions, unlocking a new dimension of possibilities for developers and projects alike.</p><h3>Prerequisites</h3><p>Before diving in, make sure you’re familiar with:</p><ul><li>Basic Ethereum smart contract development.</li><li>Solidity, the language of Ethereum smart contracts.</li><li>Typescript</li><li>Hardhat</li><li>Knowledge about Pyth Network and its EVM contracts. If you’re new to Pyth Network, I’d recommend reading their introduction and understanding how it differs from other oracles.</li><li>Set up your development environment with @gelatonetwork/web3-functions-sdk and @pythnetwork/pyth-evm-js packages installed.</li></ul><h3>Introduction to Pyth on the EVM</h3><p>Pyth Network offers a unique solution to bring real-world pricing information onto the blockchain. But how does it achieve this? Simply put, Pyth works through a three-tiered mechanism:</p><p><strong>Publishers</strong>: These entities push pricing data to the Pyth protocol. And to ensure accuracy, Pyth doesn’t rely on just one source. Instead, multiple publishers contribute data for each product, making the overall system more reliable.</p><p><strong>Oracle Aggregation</strong>: Once the data is in, Pyth’s oracle program steps in. It cleverly combines all the data from various publishers, culminating in a single cohesive price, complemented by a confidence interval. This process ensures that the final data is not only accurate but also representative of a broad consensus.</p><p><strong>Consumers</strong>: Finally, we have the end-users. These consumers tap into the Pyth Network to retrieve the vetted pricing information produced by the oracle program, allowing for informed decision-making on the blockchain.</p><p>By facilitating this structured interaction between publishers, the oracle, and consumers, Pyth ensures a steady flow of precise and trustworthy pricing data for all its users.</p><p>For those keen on diving deeper into the intricacies of the Pyth Network, I’d recommend exploring their comprehensive documentation available <a href="https://docs.pyth.network/documentation">here</a>.</p><h3>Deep Dive into the Code</h3><p>Using the Web3 Functions SDK and Ethers.js, we can initiate a connection with the Pyth Network on the Ethereum Virtual Machine (EVM).</p><pre>// Disabling specific TypeScript linter rule<br>/* eslint-disable @typescript-eslint/naming-convention */<br><br>// Importing necessary libraries and modules<br>import {<br>  Web3Function,<br>  Web3FunctionContext,<br>} from &quot;@gelatonetwork/web3-functions-sdk&quot;;<br>import { Contract, utils } from &quot;ethers&quot;;<br>import { EvmPriceServiceConnection } from &quot;@pythnetwork/pyth-evm-js&quot;;<br>import { IPyth } from &quot;../../typechain&quot;;<br>import { pythAbi } from &quot;./pythAbi&quot;;<br><br>// Define an interface for our price structure<br>interface IPRICE {<br>  price: number;<br>  timestamp: number;<br>}<br><br>// Main function that runs when Web3Function is invoked<br>Web3Function.onRun(async (context: Web3FunctionContext) =&gt; {<br>  // Destructuring necessary properties from the context<br>  const { userArgs, storage, secrets, multiChainProvider } = context;<br><br>  // Get the default provider from the multiChainProvider<br>  const provider = multiChainProvider.default();<br><br>  // Retrieve the last price from user&#39;s storage or default to an empty object<br>  const lastPrice = JSON.parse(<br>    (await storage.get(&quot;lastPrice&quot;)) ?? &quot;{}&quot;<br>  ) as IPRICE;<br><br>  // Get Pyth network address from user arguments or default to an empty string<br>  const pythNetworkAddress = (userArgs.pythNetworkAddress as string) ?? &quot;&quot;;<br><br>  // Initializing the Pyth Network contract instance<br>  const pythnetwork = new Contract(<br>    pythNetworkAddress,<br>    pythAbi,<br>    provider<br>  ) as IPyth;<br><br>  // Extracting price IDs from user arguments<br>  const priceIds = (userArgs.priceIds ?? &quot;&quot;) as string[];<br><br>  // Creating a connection to the Pyth Price Service on their testnet<br>  const connection = new EvmPriceServiceConnection(<br>    &quot;https://xc-testnet.pyth.network&quot;<br>  );<br><br>  // Fetching the latest price feeds from the connection<br>  const check = (await connection.getLatestPriceFeeds(priceIds)) as any[];<br><br>  // Check if price data is available, if not return an error message<br>  if (!check.length || !check[0].price || !check[0].price.price) {<br>    return { canExec: false, message: &quot;No price available&quot; };<br>  }<br><br>  // Extract the current price and its timestamp from the fetched data<br>  const currentPrice: IPRICE = {<br>    price: +check[0].price.price,<br>    timestamp: +check[0].price.publishTime,<br>  };<br><br>  // If no last price exists in the storage, initialize with the current price<br>  if (lastPrice.price == undefined) {<br>    await storage.set(&quot;lastPrice&quot;, JSON.stringify(currentPrice));<br><br>    const updatePriceData = await connection.getPriceFeedsUpdateData(priceIds);<br>    console.log(&quot;Web3 Function price initialization&quot;);<br><br>    // Get the fee required for the update operation<br>    const fee = (await pythnetwork.getUpdateFee(updatePriceData)).toString();<br><br>    // Prepare the call data for the update operation<br>    const callData = await pythnetwork.interface.encodeFunctionData(<br>      &quot;updatePriceFeeds&quot;,<br>      [updatePriceData]<br>    );<br><br>    return {<br>      canExec: true,<br>      callData: [<br>        {<br>          to: pythNetworkAddress,<br>          data: callData,<br>          value: fee,<br>        },<br>      ],<br>    };<br>  }<br><br>  // Constants and calculations for price comparison logic<br>  const dayInSec = 24 * 60 * 60;<br>  const diff = Math.abs(lastPrice.price - currentPrice.price) / lastPrice.price;<br><br>  // If price difference is greater than 2% or 24h have elapsed, update the price on-chain<br>  if (diff &gt;= 0.02 || currentPrice.timestamp - lastPrice.timestamp &gt; dayInSec) {<br>    const updatePriceData = await connection.getPriceFeedsUpdateData(priceIds);<br>    const callData = await pythnetwork.interface.encodeFunctionData(<br>      &quot;updatePriceFeeds&quot;,<br>      [updatePriceData]<br>    );<br>    const fee = (await pythnetwork.getUpdateFee(updatePriceData)).toString();<br>    console.log(`Updating Price:${currentPrice.price}`);<br><br>    // Update the storage with the current price<br>    await storage.set(&quot;lastPrice&quot;, JSON.stringify(currentPrice));<br><br>    return {<br>      canExec: true,<br>      callData: [<br>        {<br>          to: pythNetworkAddress,<br>          data: callData,<br>          value: fee,<br>        },<br>      ],<br>    };<br>  } else {<br>    // If none of the update conditions are met, return a message indicating the same<br>    return {<br>      canExec: false,<br>      message: `No conditions met for price Update, price diff = ${(<br>        100 * diff<br>      ).toFixed(2)}%`,<br>    };<br>  }<br>});</pre><p>Here’s what each section of the code does:</p><ul><li><strong>Initialization</strong>: Establishing the necessary libraries and setting up the main interface structures.</li><li><strong>Setting up the Web3 function</strong>: Accessing user arguments, storage, secrets, and the multiChainProvider from the function’s context.</li><li><strong>Fetching and Checking Prices</strong>: Using the EvmPriceServiceConnection to interact with the Pyth Network and obtain the latest prices.</li><li><strong>Price Update Logic</strong>: Evaluates if the price should be updated based on the difference from the last recorded price or if 24 hours have passed.</li></ul><h3>4. Conclusion and Next Steps</h3><p>Understanding how different networks can interoperate is crucial in today’s fragmented blockchain ecosystem. By leveraging the Gelato Network’s capabilities with the Pyth Network’s reliable data feeds, developers can unlock a myriad of DeFi use cases.</p><p>For those looking for a visual walkthrough, check out our comprehensive YouTube tutorial covering this integration.</p><h3>Key Resources:</h3><ul><li><a href="https://github.com/gelatodigital/w3f-pyth-poc-v2">Gelato Pyth PoC Repository</a>: The heart of this integration. Dive deep into the source code.</li><li><a href="https://docs.gelato.network/developer-services/web3-functions">Web3 Functions Documentation</a>: All you need to know about Web3 Functions.</li><li><a href="https://pyth.network/">Pyth Network Documentation</a>: A detailed guide on Pyth Network and its offerings in the DeFi space.</li></ul><p>Stay tuned for more insights and deep dives into the world of Web3!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760cc96126ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap: A Deep Dive Into Its Data and Control Flows]]></title>
            <link>https://medium.com/coinmonks/uniswap-a-deep-dive-into-its-data-and-control-flows-69fbf2c5b02a?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/69fbf2c5b02a</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[uniswap-v2]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 06:43:20 GMT</pubDate>
            <atom:updated>2023-08-24T06:43:20.420Z</atom:updated>
            <content:encoded><![CDATA[<p>Uniswap has taken the DeFi sector by storm, offering a decentralized protocol for token exchange on Ethereum. For the uninitiated, the intricate workings of Uniswap might seem perplexing. In this article, we will break down the data and control flow of its three main actions: <strong>swapping tokens</strong>, <strong>adding liquidity</strong>, and <strong>removing liquidity</strong>.</p><h3>Swapping tokens on Uniswap</h3><p>Swapping tokens is a frequent action on Uniswap and the most common flow, mainly executed by traders. Here’s a step-by-step breakdown:</p><h4>The Caller’s Action</h4><ol><li>Allow the periphery to access the amount you’re swapping.</li><li>Choose a swap function from the periphery. The choice depends on factors like if ETH’s part of the deal, how many tokens you’re giving, or what you expect in return. Each function uses a ‘path’, a list of the exchanges involved.</li></ol><h4>The Periphery Contract: UniswapV2Router02.sol’s Role</h4><ol><li>Figure out how many tokens need to be swapped at each step.</li><li>Walk through the path. At each step, it sends the input tokens and triggers the swap. Tokens usually move to the next exchange, but at the last step, they go to the trader’s address.</li></ol><h4>In the Core (UniswapV2Pair.sol):</h4><ol><li>Check to ensure enough liquidity remains after the swap.</li><li>Count any tokens over the known reserves, which is the swap’s input.</li><li>Dispatch the swapped tokens.</li><li>Update the reserve counts.</li></ol><h4>Back in the Periphery:</h4><p>Clean up any remaining tasks, like converting WETH tokens back to ETH.</p><h4>Talk is cheap, show me the code!</h4><pre>const tx = await router<br>    .connect(owner)<br>    .swapExactTokensForTokens(<br>      ethers.parseUnits(&quot;1&quot;, 18),<br>      0,<br>      [USDT_ADDRESS, USDC_ADDRESS],<br>      owner.address,<br>      Math.floor(Date.now() / 1000) + 60 * 10,<br>      {<br>        gasLimit: 1000000,<br>      }<br>    );<br>await tx.wait();</pre><p>Here is a sample code that demonstrates how the actual swap happens. The user is trying to swap an exact amount of USDT for USDC.</p><ul><li>The first parameter ethers.parseUnits(&quot;1&quot;, 18) denotes the exact amount of USDT to be swapped (1 USDT in this case).</li><li>The second parameter 0 is the minimum amount of USDC expected to be received in return. It&#39;s set to 0, indicating any amount of USDC is acceptable.</li><li>The next two parameters [USDT_ADDRESS, USDC_ADDRESS] specify the trading path.</li><li>The subsequent parameter is the recipient’s address, in this case, the owner.</li><li>The last parameter in the list is a deadline (current timestamp + 10 minutes), after which the transaction will not go through.</li></ul><h3>Adding Liquidity on Uniswap</h3><h4>The Caller’s Action</h4><ol><li>Let the periphery access the tokens you’re putting into the liquidity pool.</li><li>Use a function from the periphery to add those tokens.</li></ol><h4>Within the Periphery (UniswapV2Router02.sol):</h4><ol><li>Make a new token pair if needed.</li><li>For an existing pair, figure out how many of each token to add, keeping the same ratio.</li><li>Ensure the amount you’re adding meets any specified minimum.</li><li>Engage the core contract.</li></ol><h4>In the Core (UniswapV2Pair.sol):</h4><ol><li>Mint new liquidity tokens and give them to the caller.</li><li>Refresh the reserve counts.</li></ol><h4>Talk is cheap, show me the code!</h4><pre>const addLiquidityTx = await router<br>    .connect(owner)<br>    .addLiquidity(<br>      usdtAddress,<br>      usdcAddress,<br>      token0Amount,<br>      token1Amount,<br>      0,<br>      0,<br>      owner,<br>      deadline<br>    );</pre><p>The addLiquidity function requires the addresses of the two tokens, the amount of each token to be added, the minimum amounts of each token to be added (set to 0 for simplicity), the address receiving the liquidity provider (LP) tokens, and a deadline after which the transaction will not execute.</p><h3>Removing Liquidity on Uniswap</h3><h4>The Caller’s Action</h4><ol><li>Allow the periphery to take the liquidity tokens you’re cashing out.</li><li>Use a function from the periphery to remove liquidity.</li></ol><h4>Within the Periphery (UniswapV2Router02.sol):</h4><p>Pass on the liquidity tokens to the pair exchange.</p><h4>In the Core (UniswapV2Pair.sol):</h4><ol><li>Based on the liquidity tokens given up, send back the equivalent underlying tokens. For instance, if giving up 10% of your liquidity tokens, you get 10% of each token in the pool.</li><li>Destroy (burn) the cashed-out liquidity tokens.</li><li>Update the reserve counts.</li></ol><h4>Talk is cheap, show me the code!</h4><pre>    const removeLiquidityTx = await router.removeLiquidity(<br>        usdtAddress,<br>        usdcAddress,<br>        lpTokenBalance, // Removing all LP tokens<br>        minToken0Amount,<br>        minToken1Amount,<br>        owner.address,<br>        deadline<br>    );</pre><p>Remove Liquidity: Using the removeLiquidity function, we specify the token addresses, the amount of LP tokens we want to burn, the minimum amounts of each token we want in return (set to 0 for the example), the address that will receive the tokens, and a deadline.</p><p>Uniswap is a standout player in the DeFi world, making decentralized token exchanges on Ethereum straightforward and efficient. Through this article, we’ve broken down its inner workings, from token swaps to adding or removing liquidity. Alongside the explanations, we provided hands-on code examples to showcase how these operations play out in real life. Whether you’re a developer, trader, or just curious about DeFi, we hope this guide has made Uniswap a bit easier to grasp. Remember, understanding tools like Uniswap is a stepping stone to navigating the broader crypto ecosystem with confidence.</p><p>Toodles! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69fbf2c5b02a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/uniswap-a-deep-dive-into-its-data-and-control-flows-69fbf2c5b02a">Uniswap: A Deep Dive Into Its Data and Control Flows</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy & Interact with Uniswap V2 Pair Locally with Hardhat and Ethers.js v6]]></title>
            <link>https://medium.com/coinmonks/deploy-interact-with-uniswap-v2-pair-locally-with-hardhat-and-ethers-js-v6-f8f5dd436930?source=rss-c8296a5bbaec------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8f5dd436930</guid>
            <category><![CDATA[hard-hat]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[uniswap-v2]]></category>
            <category><![CDATA[ethersjs]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Anirudh Makhana]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 08:00:45 GMT</pubDate>
            <atom:updated>2023-08-22T14:54:27.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*B4Fs2HIQGXHHz6eP8-44Cw.png" /></figure><h3>Introduction</h3><p>Fresh out of college, armed with a degree and a fervor to make my mark in the rapidly evolving world of web3, I began applying for various roles in the sector. My enthusiasm soon led me to an interview for a position that required deep knowledge of the web3 yield farming protocols, specifically the intricacies of Uniswap V2. I still remember that intense moment during my job interview at a web3 yield farming protocol. As my interviewer’s face filled the screen, they posed a challenge: “Can you explain the Uniswap V2 code to us?” and “Write me a script that allows users to mint” My heart rate climbed. While I had dabbled with DeFi and blockchain, I wasn’t entirely familiar with the intricate details of the Uniswap V2 codebase. Unfortunately, this gap in my knowledge cost me the job.</p><p>However, instead of letting that experience dampen my spirit, I decided to take it as an opportunity to learn and grow. And so, this article was born. In the next few sections, I’ll walk you through the high-level steps to deploy a decentralized exchange using Ethers.js and Hardhat, sharing my journey of understanding the inner workings of protocols akin to Uniswap.</p><h3>Overview of the Process</h3><ol><li><strong>Setup</strong>: Before diving in, ensure you’ve set up the necessary environment. This includes importing essential modules and contract artifacts.</li><li><strong>Retrieving Signers</strong>: This is where we gain access to the Ethereum accounts available to us. For this demonstration, the first account is considered the owner.</li><li><strong>Factory Deployment</strong>: The Factory contract in Uniswap-like protocols is responsible for creating pairs of tokens that can be traded against each other.</li><li><strong>ERC20 Token Deployments</strong>: A decentralized exchange would be incomplete without fungible tokens. For our purpose, we’ve chosen popular stablecoins, USDT and USDC.</li><li><strong>Creating Trading Pairs</strong>: After deploying our tokens, we use the Factory contract to create a trading pair between USDT and USDC.</li><li><strong>Liquidity Provision</strong>: To allow trading, our newly created trading pair requires liquidity. In our setup, we mint additional tokens and add them as liquidity to the trading pool.</li><li><strong>Router Setup</strong>: The Router contract handles the trading logic in Uniswap-like protocols. It needs to be initialized with the address of the Factory contract and the WETH9 contract (a wrapped version of ETH).</li><li><strong>Finalizing and Execution</strong>: With everything set up, we finally execute our deployment script using Hardhat.</li></ol><h4>Prerequisites</h4><ul><li>Basic understanding of Ethereum smart contracts</li><li><strong>Deep </strong>understanding of Uniswap V2 core contracts</li><li>Familiarity with Ethers.js and Hardhat</li><li>Installed Node.js and npm on your system</li></ul><h3>Understanding Uniswap v2 core contracts</h3><p>Uniswap V2 is a decentralized protocol built on Ethereum, known for its automated liquidity provision. It comes as an improvement over the initial Uniswap V1, offering enhanced features and capabilities. Here’s a brief overview of its core contracts:</p><h4>Factory Contract</h4><p><strong>Purpose</strong>: At its core, the Factory contract’s role is to produce individual pair contracts for each unique combination of tokens.</p><p><strong>Functionality</strong>: Anytime a new pair is needed, it’s created through this Factory contract. It maintains a record of all pairs created, ensuring easy access and retrievability.</p><h4>Pair Contract</h4><p><strong>Purpose</strong>: Represents a liquidity pool for two ERC20 tokens. Each unique token combination has its own Pair contract.</p><p><strong>Functionality</strong>:</p><ul><li>Liquidity: Users can add or remove liquidity to a pair. In return for providing liquidity, they receive LP (Liquidity Provider) tokens.</li><li>Swapping: Allows users to swap between the two tokens. The swap rates are determined algorithmically based on the relative supply of the tokens in the pool.</li><li>Price Oracle: Uniswap V2 introduces a manipulation-resistant price oracle that averages prices over a time period, making it harder for malicious actors to manipulate prices.</li></ul><h3>Getting Started</h3><p>As part of the project, I created two ERC20 tokens to simulate real-world assets in the Ethereum ecosystem: UsdCoin (symbolized as USDC) and Tether (symbolized as USDT). Here&#39;s a implementation:</p><p><strong>USDC.sol</strong></p><pre>//SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import &#39;@openzeppelin/contracts/token/ERC20/ERC20.sol&#39;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract UsdCoin is ERC20, Ownable {<br>  constructor() ERC20(&#39;UsdCoin&#39;, &#39;USDC&#39;) {}<br><br>  function mint(address to, uint256 amount) public onlyOwner {<br>    _mint(to, amount);<br>  }<br>}</pre><p><strong>USDT.sol</strong></p><pre>//SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import &#39;@openzeppelin/contracts/token/ERC20/ERC20.sol&#39;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br><br>contract Tether is ERC20, Ownable {<br>  constructor() ERC20(&#39;Tether&#39;, &#39;USDT&#39;) {}<br><br>  function mint(address to, uint256 amount) public onlyOwner {<br>    _mint(to, amount);<br>  }<br>}</pre><h3>Writing the deploy script</h3><p>First, ensure you have imported the necessary modules and contract artifacts:</p><pre>const { Contract, ContractFactory } = require(&quot;ethers&quot;);<br>const WETH9 = require(&quot;../WETH9.json&quot;);<br>const factoryArtifact = require(&quot;@uniswap/v2-core/build/UniswapV2Factory.json&quot;);<br>const routerArtifact = require(&quot;@uniswap/v2-periphery/build/UniswapV2Router02.json&quot;);<br>const pairArtifact = require(&quot;@uniswap/v2-periphery/build/IUniswapV2Pair.json&quot;);<br>const { ethers } = require(&quot;hardhat&quot;);</pre><p><strong>Main deployment function</strong></p><pre>async function main() {<br>  // Your deployment code goes here...<br>}</pre><p><strong>Retrieving Signers</strong></p><p>The first step is to retrieve the signers from the ethers provider. We’ll consider the first signer as the ‘owner’ for simplicity:</p><pre>const [owner] = await ethers.getSigners();<br>console.log(`Deploying contracts with the account: ${owner.address}`);</pre><p><strong>Factory Deployment</strong></p><p>Initiate the Uniswap V2 Factory contract and deploy it using the ABI and bytecode:</p><pre>const Factory = new ContractFactory(<br>  factoryArtifact.abi,<br>  factoryArtifact.bytecode,<br>  owner<br>);<br>const factory = await Factory.deploy(owner.address);</pre><p><strong>ERC20 Token Deployments</strong></p><p>Proceed to deploy the ERC20 tokens, USDT and USDC:</p><pre>const USDT = await ethers.getContractFactory(&quot;Tether&quot;, owner);<br>const usdt = await USDT.deploy();<br>const usdtAddress = await usdt.getAddress();<br>console.log(`USDT deployed to ${usdtAddress}`);<br><br>const USDC = await ethers.getContractFactory(&quot;UsdCoin&quot;, owner);<br>const usdc = await USDC.deploy();<br>const usdcAddress = await usdc.getAddress();<br>console.log(`USDC deployed to ${usdcAddress}`);</pre><p>Once the Factory contract and the two ERC20 tokens are successfully deployed, our next step is to deploy the Router contract. This Router contract specifically requires the addresses of both the Factory contract and the WETH9 contract. It’s worth noting that the WETH9 contract serves as a wrapper for the native Ethereum token, ETH. However, before proceeding with the deployment of the Router, there’s an essential preparatory step. We first need to mint a certain amount of USDT and USDC tokens and allocate them to the owner.</p><p><strong>Minting tokens to owner</strong></p><p>For testing purposes, you mint 1000 USDT and USDC tokens and send them to the owner’s address.</p><pre>await usdt.connect(owner).mint(owner.address, ethers.parseEther(&quot;1000&quot;));<br>await usdc.connect(owner).mint(owner.address, ethers.parseEther(&quot;1000&quot;));</pre><p><strong>Creating a Trading Pair</strong></p><p>Using the Factory contract, you initiate a trading pair using the addresses of USDT and USDC.</p><pre>const tx1 = await factory.createPair(usdtAddress, usdcAddress);<br>await tx1.wait();<br>const pairAddress = await factory.getPair(usdtAddress, usdcAddress);<br>console.log(`Pair deployed to ${pairAddress}`);<br><br>// Initialize a new contract instance for the trading pair using its address and ABI.<br>const pair = new Contract(pairAddress, pairArtifact.abi, owner);</pre><p><strong>Liquidity Provision</strong></p><p>To allow trading, our newly created trading pair requires liquidity. In our setup, we mint additional tokens and add them as liquidity to the trading pool.</p><pre>// Query the reserves of the trading pair to check liquidity.<br>let reserves = await pair.getReserves();<br>console.log(`Reserves: ${reserves[0].toString()}, ${reserves[1].toString()}`); //This should be 0,0 since we haven&#39;t provided the liquidity to the pair / pool yet.</pre><p><strong>Router Setup</strong></p><p>The Router contract handles the trading logic in Uniswap-like protocols. It needs to be initialized with the address of the Factory contract and the WETH9 contract (a wrapped version of ETH).</p><pre>const Router = new ContractFactory(<br>    routerArtifact.abi,<br>    routerArtifact.bytecode,<br>    owner<br>  );<br><br>const router = await Router.deploy(factoryAddress, wethAddress);<br>  const routerAddress = await router.getAddress();<br>  console.log(`Router deployed to ${routerAddress}`);<br><br>  const MaxUint256 =<br>    &quot;0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff&quot;;<br><br>  const approveTx1 = await usdt.approve(routerAddress, MaxUint256);<br>  await approveTx1.wait();<br>  const approvalTx2 = await usdc.approve(routerAddress, MaxUint256);<br>  await approvalTx2.wait();<br><br>  const token0Amount = ethers.parseUnits(&quot;100&quot;);<br>  const token1Amount = ethers.parseUnits(&quot;100&quot;);<br><br>  const deadline = Math.floor(Date.now() / 1000) + 10 * 60;<br>  const addLiquidityTx = await router<br>    .connect(owner)<br>    .addLiquidity(<br>      usdtAddress,<br>      usdcAddress,<br>      token0Amount,<br>      token1Amount,<br>      0,<br>      0,<br>      owner,<br>      deadline<br>    );<br>  await addLiquidityTx.wait();<br>  reserves = await pair.getReserves();<br>  console.log(`Reserves: ${reserves[0].toString()}, ${reserves[1].toString()}`);</pre><p><strong>Finalizing and Execution</strong></p><p>With everything set up, we finally execute our deployment script using Hardhat.</p><pre>npx hardhat run --network localhost scripts/deploy.js</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*8UvMeVfjWZ93Wnb_PuWJsA.png" /><figcaption>Logs from terminal when running the deploy script</figcaption></figure><h3>Conclusion</h3><p>Setting up a decentralized exchange might seem complex, but with tools like Ethers.js and Hardhat, the process becomes more manageable. The beauty of open-source and the Ethereum community is the collective knowledge and shared resources, allowing anyone to kickstart their DeFi journey. Feel free to explore the provided GitHub repository and expand upon it for your projects.</p><p>Check out the code on GitHub here:</p><p><a href="https://github.com/anirudhmakhana/UniswapV2">GitHub - anirudhmakhana/UniswapV2</a></p><p>Toodles! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8f5dd436930" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/deploy-interact-with-uniswap-v2-pair-locally-with-hardhat-and-ethers-js-v6-f8f5dd436930">Deploy &amp; Interact with Uniswap V2 Pair Locally with Hardhat and Ethers.js v6</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>