<?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 lakshya kumar on Medium]]></title>
        <description><![CDATA[Stories by lakshya kumar on Medium]]></description>
        <link>https://medium.com/@lklsquare?source=rss-d7d477cfa30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qjAl2nHHaEaxEUQpw4-TgQ.png</url>
            <title>Stories by lakshya kumar on Medium</title>
            <link>https://medium.com/@lklsquare?source=rss-d7d477cfa30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:26:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lklsquare/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[We Took One App From 12 Users to 100,000. Here’s Every Time It Broke.]]></title>
            <link>https://medium.com/@lklsquare/we-took-one-app-from-12-users-to-100-000-heres-every-time-it-broke-be11aa38610d?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/be11aa38610d</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 02:27:37 GMT</pubDate>
            <atom:updated>2026-09-13T02:27:37.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MfKQThAuT4i2wSXS" /><figcaption>Photo by <a href="https://unsplash.com/@rahuulmiishra?utm_source=medium&amp;utm_medium=referral">Rahul Mishra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>A build log, in order. The app is a prop. The failures are real, and they arrive in a predictable sequence.</strong></p><p>Most scaling articles show you the finished architecture. Load balancer here, cache there, a queue in the middle, arrows everywhere. It’s tidy, and it’s useless — because you don’t have that app, and you never lived through the problem that made each box on the diagram necessary.</p><p>So let’s do it the other way round. We’re going to build one small app, put it on the internet, and grow it. Every time it breaks, we’ll sit with the failure, work out why it happened, and fix it. Nothing gets added to the stack until something forces it.</p><p>The app is <strong>Brewlog</strong> — a coffee brewing journal. You log a brew: beans, grind, time, notes, a photo. You follow people. You comment. That’s the whole product. It is deliberately unremarkable, because the failures we’re chasing don’t care what your app does.</p><p>One number before we start. At 100,000 users, Brewlog peaks at around <strong>140 requests per second</strong>. That is not big. It is a single modest server’s worth of traffic. And it still took the site down four separate times.</p><p>That’s the point of this piece. You do not need Google’s traffic to hit these walls. You need <em>slightly more traffic than you had last month</em>.</p><h3>Week 0 | Build It</h3><p>One small virtual machine. One managed database. A reverse proxy in front handling encryption. Deploys are a git pull and a restart.</p><p>Four tables: users, brews, comments, follows. Six endpoints. It took a weekend.</p><p>And in that weekend we make four decisions without thinking about them at all:</p><ul><li><strong>The database connection pool is set to 100</strong>, a number copied from a tutorial.</li><li><strong>Login sessions are kept in the app’s own memory</strong>, because that’s the default.</li><li><strong>Uploaded photos are written to the server’s local disk.</strong></li><li><strong>Notification emails are sent inside the request</strong>, while the user waits.</li></ul><p>Not one of these is wrong at twelve users. Every one of them is a load-bearing bug by thirty thousand. Keep them in mind — they all come back.</p><h3>Week 1 | 12 Users — The site is down and nobody deployed anything</h3><p>Day four. A friend messages: <em>site’s down?</em></p><p>It is. I log into the server and the app simply isn’t running. There’s no crash log, because I never set up logging. Nothing restarted it, because nothing was watching it.</p><p>What happened is that I’d started the app by hand from my laptop over a remote shell, and left it running in the background. Days later that background process died — killed with the terminal, or out of memory, I genuinely never found out. Not knowing is itself the lesson.</p><blockquote><strong><em>The fix is a process supervisor.</em></strong><em> Every operating system ships one. It starts your app on boot, restarts it when it dies, and captures its output so a crash leaves a body behind. Starting something by hand and hoping it stays up is not deployment, it’s optimism.</em></blockquote><h3>And then, two days later, the one that actually scared me</h3><p>Cleaning up test accounts. In production. At eleven at night. I deleted one user’s brews and the database reported 847 rows removed.</p><p>There weren’t supposed to be 847. I’d used the wrong ID. Those were real brews, from real people who had been using this thing for a week.</p><p>We got them back, because the managed database had continuous backups switched on by default. That was luck, not planning. I had never tested a restore. I did not know whether the backups worked, how long a recovery would take, or how much data I’d lose in the process. I found out all three while sweating.</p><p><strong>The fix is a restore drill, and it takes twenty minutes.</strong> Restore yesterday’s backup into a scratch database. Time how long it takes. Look at the newest record in it and see how far behind the live system it is. Those two numbers are your real recovery time and your real data-loss window, and until you’ve measured them, you don’t have backups — you have a <em>feeling</em> that you have backups.</p><p>Ours were eight minutes and four minutes. We wrote both on the front page of the README.</p><p><strong>Two other things went in that evening</strong>, neither of which mattered yet:</p><ol><li>Database changes moved into version-controlled migration files instead of being typed into a console by hand. The version where you skip this involves reverse-engineering your own schema from production at 2 AM.</li><li>We added two health endpoints that look identical and mean completely different things. One says <em>this process is alive</em>. The other says <em>I can actually serve traffic right now — my database connection works, my start-up finished</em>. Conflating them means your infrastructure sends real users to a server that isn’t ready for them. Useless in week one. Load-bearing in month seven.</li></ol><h3>Week 3 | 140 Users — “It was broken this morning”</h3><p>An email: <em>tried to post a brew around 9am, got an error page. Works now.</em></p><p>And I have nothing. My logs are a stream of half-sentences from every request at once, with no timestamps, no user, no way to tell which line belongs to which visit. I cannot tell that person what happened. I cannot tell myself either.</p><p><strong>This is the real failure of this stage. Not the outage — the blindness.</strong></p><p>Three things fix it, and together they’re a weekend.</p><ul><li><strong>Logs with structure.</strong> The difference between a log you read and a log you can <em>search</em>. Instead of scattering sentences, every request emits one record with consistent fields: who, what route, how long, what status, what went wrong. The content barely changes. What changes is that you can now ask questions of it.</li><li><strong>A request ID.</strong> A unique tag generated the moment a request arrives, attached to every log line that request produces, and passed along to anything it calls. Show it on your error page. Now a user pastes a code into an email, you paste it into your log search, and the entire story of that request comes back in one result. One extra field, and guesswork stops being part of the job. It’s the best return on effort on this whole list.</li><li><strong>Four numbers on one dashboard.</strong> How fast (latency), how much (traffic), how often it fails (errors), how full things are (saturation). Nothing clever. The point is having somewhere to look that isn’t the app itself.</li></ul><h4>Then I made a four-week mistake</h4><p>I imported a monitoring template. Thirty-one alert rules, all of them sensible-sounding.</p><p>Within a fortnight, the alerts channel was firing forty times a day. Disk at 71 percent. A single error from a bot probing for a login page that doesn’t exist. Processor above 60 percent for one minute. I muted the channel. Then everyone muted the channel.</p><p>And then a real one fired — the database was unreachable for twenty minutes — and we found out from a user.</p><p>An alert is a contract: <em>I will interrupt you, because a human needs to make a decision now.</em> Thirty-one alerts is not a stricter contract. It is no contract at all, because the value of an alert is entirely destroyed by the ones next to it that didn’t matter.</p><p>We deleted all thirty-one and wrote three:</p><ul><li><strong>Error rate:</strong> Above 1% of requests for 5 minutes <em>(Means something is broken)</em></li><li><strong>Latency:</strong> Slowest 1% above 2 seconds for 10 minutes <em>(Means something is slow)</em></li><li><strong>Dependency:</strong> The readiness check failing for 5 minutes <em>(Means the database is gone)</em></li></ul><p>The test is completely literal: <strong>would I want to be woken at three in the morning for this?</strong> If the honest answer is no, it is a ticket, a dashboard, or a Monday problem. It is not an alert.</p><h3>Week 7 | 1,100 Users — The Wall</h3><p>A newsletter links us. Traffic quadruples in an hour, and the site starts failing in bursts — fine, broken, fine, broken. The logs say the database is refusing new connections. There are none left.</p><h4>The diagnosis, and the counter-intuitive fix</h4><p>Our database allowed a hundred simultaneous connections. Our connection pool was set to a hundred — that number from week zero — and we were running three copies of the app to use the server’s cores. Three hundred wanted, one hundred available.</p><p>The obvious move is to raise the limit. That is the wrong move, and understanding why is probably the most useful thing in this article.</p><p>A connection to a database like Postgres is not free or lightweight. Each one gets its own operating-system process and its own slice of memory, and the database’s genuinely useful concurrency is bounded by how many processor cores it has — realistically a small multiple of them. On a two-core machine that’s somewhere under a dozen.</p><p>So three hundred connections does not buy you capacity. It buys you three hundred queries fighting over two cores, plus all the overhead of switching between them. The work doesn’t get done faster. It gets done in a worse order, with everyone waiting.</p><p>We tested in both directions and the result still surprises people:</p><ul><li><strong>100 → 300 total connections:</strong> Resulted in failures</li><li><strong>30 → 90 total connections:</strong> 240 req/sec <em>(Slowest 1%: 410 ms)</em></li><li><strong>8 → 24 total connections:</strong> 255 req/sec <em>(Slowest 1%: 62 ms)</em></li></ul><p>A dramatically smaller pool delivered slightly <em>more</em> throughput and cut the slow tail by more than six times.</p><p>The reason is that the queueing has to happen somewhere. Too large a pool pushes it inside the database, where it’s expensive and invisible. A small pool keeps it in your app, where it’s cheap, and where you can put a number on it. So the second half of this fix is a metric: how long requests spend waiting for a free connection. That turns a mysterious slowdown into a gauge you can watch.</p><h4>With the fire out, the actual problem became visible</h4><p>Once the connection errors stopped, the feed was still slow — around 800 milliseconds. Time to stop guessing and ask the database what it was actually doing.</p><p>Every serious database can EXPLAIN its own plan for a query: what it read, in what order, how many rows it touched, where the time went. Ours reported that loading the twenty most recent brews involved reading <strong>every single one of the 486,000 rows in the table</strong>, sorting the entire lot by date, and returning the top twenty. Every time anyone loaded the homepage.</p><p>No index existed on the column we were sorting by. The database had no way to find recent brews except to look at all of them. Adding one index took that query from 813 milliseconds to under a millisecond.</p><blockquote><em>The discipline here is small and permanent: </em><strong><em>read the plan, not the query.</em></strong><em> A query that looks reasonable can be doing something catastrophic, and the plan is the only place that shows up.</em></blockquote><h4>The second bug: one page, twenty-one queries</h4><p>The feed shows each brew with its author’s name and avatar. Our database library made that lovely to write — fetch the brews, then for each brew, fetch its author.</p><p>That’s one query for the list, plus one per row. Twenty brews, twenty-one queries.</p><p>Here is why this specific bug reaches production so reliably: <strong>it is fast on your laptop for a reason that does not exist in production.</strong> Locally, the database is on the same machine and answers in a fraction of a millisecond, so twenty-one round trips cost you four milliseconds and you never notice. In production the database is across a network. Every round trip costs twelve milliseconds whether it does any work or not, and the same page now spends a quarter of a second doing nothing but waiting.</p><p>The fix is one instruction to fetch the authors alongside the brews rather than after them — twenty-one queries become two.</p><p>The fix isn’t the valuable part, though. The detection is. We added a counter that reports how many queries each request made, and a check that fails our build if any page’s query count grows with the number of rows it returns. <strong>If the number of queries is a function of the size of the result, you have this bug.</strong> That rule catches it forever.</p><h4>The third bug: pagination got slower the deeper you scrolled</h4><p>Infinite scroll. The first page came back in 40 milliseconds. The fiftieth took nearly two seconds.</p><p>The standard way to paginate is to tell the database to skip the first N rows and return the next twenty. The problem is that “skip” is not cheap. To skip a thousand rows, the database reads a thousand rows and throws them away. To skip a hundred thousand, it reads a hundred thousand. The cost of page N grows linearly with N — so your most engaged readers, the ones who scroll deepest, get the worst experience you offer.</p><p>The alternative is to stop thinking in page numbers. Instead of “give me page 50,” the client says “give me what comes after the last item I saw.” Because the list is ordered and indexed, the database jumps straight to that position and reads twenty rows. It costs the same at any depth.</p><p>You give up the ability to jump to page 47, which nobody was doing, in exchange for pagination that never degrades.</p><h4>And the quiet one</h4><p>A background job was opening a database transaction, updating a record, calling an external service that took the better part of a second, and only then committing.</p><p>A transaction is a held claim. For as long as it’s open it locks the rows it touched and prevents the database from cleaning up old versions of data. Wrapping someone else’s network call inside one means your database’s housekeeping is now hostage to a third party’s response time.</p><p>At a thousand users that’s a curiosity. At thirty thousand it’s a table growing faster than the database can tidy it. The rule: do the slow external thing first, then open the transaction, and keep transactions to the work that genuinely has to happen together.</p><p><strong>Week 7’s scorecard: the feed went from 2,400 milliseconds to 90. We added no new infrastructure at all.</strong> Four bugs and one configuration number.</p><h3>Month 4 | 12,000 Users — We add a cache and make things worse</h3><p>The trending page — top brews of the week — is an expensive calculation. It takes 180 milliseconds and it runs on every homepage load. An obvious candidate for caching: compute it once, keep the answer in memory for five minutes, serve everyone from that.</p><p>We shipped it. Latency dropped. Everybody was pleased.</p><p>Then the database’s processor graph started doing something strange: flat at eight percent, flat, flat, then a spike to ninety-four — and then flat again. Every five minutes. On the dot.</p><p>The cause, once you see it, is almost funny. When the cached answer expires, it doesn’t expire for one visitor. It expires for everyone at the same instant. Every request in flight at that moment finds nothing in the cache, and every one of them independently decides to recompute it. Around ninety copies of the same expensive calculation, launched simultaneously, at a database that was previously doing nothing.</p><p>This is a <strong>cache stampede</strong>, and it’s worth stating plainly: <strong>adding a cache made our worst case worse than having no cache at all.</strong> Without it, the load was steady and modest. With it, the load was a hammer blow every three hundred seconds.</p><p>Two fixes, both small:</p><ol><li><strong>Stagger the expiry.</strong> Add a little randomness to every cache lifetime — say plus or minus ten percent. Now your popular entries don’t all expire on the same tick of the clock. It’s the smallest change on this list and it removes an entire class of synchronised failure.</li><li><strong>Let one request do the work.</strong> When the cache misses, the first request through starts rebuilding and every other request for the same thing waits for that result instead of starting its own. One recomputation instead of ninety.</li></ol><p>We tested it the way you should: clear the cache, fire a hundred simultaneous requests, count how many reached the database. Before: a hundred. After: one.</p><p>We also did something we should have done first — <strong>set a target hit rate (85%) and put it on the dashboard.</strong> A cache you aren’t measuring is a cache you can’t tune, and “we added caching” is not a statement about your system, it’s a statement about your intentions.</p><h4>The read replica bug that generated support tickets</h4><p>Reads were still the overwhelming majority of our traffic, so we added a read-only copy of the database and sent all read requests to it. A cheap, standard win.</p><p>Within a day:</p><blockquote>posted my Ethiopian pourover, page reloaded, it’s gone. posted it again. now there’s two.</blockquote><p>The write went to the main database. The page reload immediately afterwards was a read, so it went to the copy — which was a couple of hundred milliseconds behind and didn’t have the new brew yet. The user saw an empty result, concluded it had failed, and posted again.</p><p>Replication lag is not a defect. It is precisely what you are buying: <strong>read capacity is paid for in staleness.</strong> Which means “can a user see their own writes immediately” becomes a decision you make deliberately, per page, rather than something that quietly changes underneath you when someone reroutes traffic.</p><p>Our fix: for a few seconds after somebody writes something, that person’s reads go to the main database. Everyone else keeps using the copy. The lag stops being visible to the one person guaranteed to notice it, and the replica still absorbs the other ninety-nine percent of reads.</p><p><strong>Also this month, almost free:</strong> photos moved behind a content delivery network, which cut the traffic reaching our own servers by seventy percent. And we taught the feed to answer “nothing has changed since you last asked” with an empty response instead of resending the same data. Bandwidth we simply stopped paying for.</p><h3>Month 5 | 18,000 Users — An email provider took us down</h3><p>Comment notifications had been sent inside the request handler since week zero. You post a comment, the app calls our email provider, waits for it to finish, and only then tells you it worked.</p><p>Our email provider had a bad afternoon. Their response time went from a tenth of a second to thirty seconds.</p><p>So did ours. Every comment request sat there holding a worker and a database connection, waiting on somebody else’s outage. Those resources are finite. They ran out. <strong>The entire site went down because a third party was slow at sending email.</strong></p><p>The lesson generalises past email: <strong>your slowest response time is the sum of everything on the request path, including the parts you don’t operate.</strong> Every synchronous call to an outside service is a piece of your reliability that you have quietly subcontracted.</p><p><strong>The fix is to get the work off the path.</strong> Anything that takes longer than a couple of hundred milliseconds and isn’t needed to answer the user doesn’t belong in the request. Save the comment, write down that an email needs sending, respond immediately. A separate worker process picks the job up and sends it. Comment posting went back to eighteen milliseconds, and stayed there the next time our provider had a wobble.</p><p>You do not need elaborate infrastructure for this at eighteen thousand users. The database you already have can hold the list of pending jobs perfectly well.</p><h4>And then our fix caused a bigger incident</h4><p>Three weeks later, a worker restarted in the middle of a batch. Jobs that had been picked up but not yet confirmed as finished went back into the queue and ran a second time.</p><p><strong>We sent about four thousand duplicate emails in ten minutes.</strong> It remains our worst day for unsubscribes by a distance.</p><p>Here’s the thing nobody tells you before your first queue: <strong>every queue worth using delivers at least once, not exactly once.</strong> Duplicates are not an edge case or a bug in your queue — they are the contract. A job can always run twice, because the alternative is a job that sometimes never runs at all, and that’s worse.</p><p>Which means safety has to live in the work itself. Before doing anything with a side effect, the worker checks whether that exact job has already been done, and if so, quietly stops. Do it twice, get the same result as doing it once.</p><p>Three more things went in at the same time, each one earned:</p><ul><li><strong>Writing the record and queueing the job became a single atomic step.</strong> We’d had comments saved with no email ever sent, and emails sent for comments that were never saved, because those were two separate operations and either could fail alone.</li><li><strong>Retries got backoff and randomness.</strong> When the provider recovered, every failed job retried at the same moment and knocked them straight back over. We had accidentally attacked our own supplier’s recovery. Wait progressively longer between attempts, and stagger those waits so everyone doesn’t retry in unison.</li><li><strong>Failed jobs got somewhere to go.</strong> One malformed job — a comment on a brew that had since been deleted — crashed the worker. The worker restarted, picked up the same job, and crashed again. A single bad message had stopped the entire queue. Now, after a handful of failures, a job is set aside for a human to look at and the line keeps moving.</li></ul><h3>Month 7 | 30,000 Users — We add a second server and everything breaks</h3><p>One machine is now both a single point of failure and a twenty-second outage every time we deploy. So: two machines, with a load balancer in front. Routine.</p><p>Within ten minutes, four things broke at once — and all four are the week-zero decisions coming due.</p><ol><li><strong>People were getting logged out at random.</strong> Sessions lived in the app’s memory. Each server had its own. Requests bouncing between them meant you were logged in about half the time.</li><li><strong>Half of all photos failed to load.</strong> Uploads were written to local disk. The upload landed on server A; the browser then asked server B for the image, and server B had never heard of it.</li><li><strong>Duplicate brews appeared</strong> — this time caused by us. We’d added a guard to stop double-submissions, and it worked by remembering in memory which users were mid-post. Two servers, two separate memories, no mutual exclusion at all.</li><li><strong>Live comment updates stopped working for most people.</strong> A long-lived connection belongs to whichever server accepted it. A comment arriving at the other one had no way to reach those users.</li></ol><p>Four different symptoms, one bug: <strong>any state that lives inside a process becomes a bug the moment there is more than one process.</strong></p><p>The audit takes an hour and it’s one question, asked about every piece of information that survives longer than a single request: <em>would this break if the next request went to a different machine?</em></p><p>Everything that answers yes has to move somewhere shared. Sessions to a shared store. Uploads to object storage with a delivery network in front. Locks to the shared store as well. Broadcasts to a publish-subscribe channel every server subscribes to.</p><p>And the readiness endpoint we wrote in week one, and hadn’t used in seven months, finally earned its place. The load balancer checks it constantly. When we want to shut a server down, we make it report “not ready” first, wait for the load balancer to notice and stop sending it traffic, let the requests already in flight finish, and only then stop the process. That’s the entire difference between a deploy that drops requests and one nobody notices.</p><p>Deploys became: take one machine out, update it, put it back, repeat. Zero user-visible errors.</p><h3>Month 11 | 100,000 Users — The twenty-two minute outage</h3><p>The one that actually hurt.</p><p>An ordinary Tuesday deploy, carrying an ordinary database change: add an index to speed up a slow page. The instruction was written the straightforward way, which was the wrong way, and it ran at twenty to ten in the morning — our busiest hour.</p><p>For twenty-two minutes:</p><ul><li><strong>Reads worked perfectly.</strong> The feed loaded. Photos loaded. <strong>The site looked completely fine.</strong></li><li><strong>Nobody could post a brew, leave a comment, or follow anyone.</strong></li><li><strong>All three of our alerts stayed silent.</strong></li></ul><p>Building an index the default way takes a lock that permits reading and blocks writing. On a table with forty million rows, that took twenty-two minutes, and every single write queued up behind it.</p><p>Most databases offer a slower, gentler version of the same operation that doesn’t block writes (e.g., CONCURRENTLY in Postgres). It exists precisely for this. We hadn&#39;t used it, because the fast-looking option is the one you reach for when you&#39;ve only ever run it against a development database with nine hundred rows in it.</p><p><strong>The alerts are the part worth dwelling on.</strong> Our error rate sat at 0.4 percent — under our one percent threshold — because writes are a small fraction of total requests. Our latency looked normal, because the blocked writes were being <em>held</em>, not failed. A total write outage hid comfortably inside metrics that averaged it away.</p><blockquote><strong><em>Averages hide exactly the failures that matter most.</em></strong><em> A number that mixes your cheap, frequent, healthy requests with your rare, critical, broken ones will tell you everything is fine right up until you read about it on social media. We added a fourth alert watching the write path on its own.</em></blockquote><h3>The twenty-two minutes were mostly not technical</h3><p>Once somebody thought to ask the database what it was currently doing, finding the stuck operation and cancelling it took about eleven seconds.</p><p>We spent the other twenty-two minutes on coordination. Three of us on a call, nobody sure who was deciding anything, two people independently running diagnostic queries against an already-struggling database, and a support inbox filling up that nobody was watching because we were all busy being heroes.</p><p>So the following week, while calm, we wrote one page:</p><ol><li><strong>Anyone can declare an incident.</strong> Declaring one unnecessarily costs nothing. Not declaring one cost us twenty-two minutes.</li><li><strong>One person is in charge, and they say so out loud.</strong> They do not debug. They decide, they keep the timeline, and they make sure two people aren’t doing the same thing.</li><li><strong>One person owns communication</strong> — status page, support inbox — and that is their entire job for the duration.</li><li><strong>Everybody else investigates and reports to the person in charge</strong>, rather than into a chat channel nobody is reading.</li></ol><p>We also added a rule to our build pipeline that rejects the dangerous form of that database change outright. <strong>The knowledge went into the pipeline instead of into somebody’s memory</strong>, which is the only version of “we’ll be more careful next time” that actually works.</p><h4>The write-up</h4><p>We wrote a post-mortem, and we wrote it blamelessly — which is a practical choice, not a kind one.</p><p>It didn’t conclude “be careful with migrations.” That’s not a finding, it’s a wish. It asked why the failure was <em>possible</em>: why a routine change could take the write path down, why nothing stopped it, why nothing told us. Each of those had a structural answer and each answer became a change.</p><p>The person who wrote the original change also wrote the post-mortem, presented it, and was thanked in it by name. That isn’t softness. If writing one costs you your standing, the next person stays quiet, investigates alone, and the next outage runs twice as long.</p><h4>After the fire: the arithmetic we should have done a year earlier</h4><p>Once things were stable, we finally measured instead of estimating.</p><p><strong>Where does one machine actually break?</strong> We load-tested a single production-shaped server with a realistic mix of traffic — weighted to the pages people actually use, not a health check in a loop — and pushed it until it fell over. The curve bends in a very particular way:</p><ul><li><strong>50 req/sec:</strong> 28 ms <em>(Slowest 1%)</em></li><li><strong>100 req/sec:</strong> 41 ms <em>(Slowest 1%)</em></li><li><strong>200 req/sec:</strong> 88 ms <em>(The knee)</em></li><li><strong>250 req/sec:</strong> 340 ms <em>(Broken)</em></li></ul><p>One machine handles about 200 requests per second for our workload. And the thing that gave out first was the processor, spending its time turning data into JSON — which is not what any of us would have guessed.</p><p><strong>Peak versus average.</strong> Our average was 40 requests per second. Our measured peak was 140 — a ratio of three and a half, driven by the European morning. You provision for the peak, not the average, and you can only know the ratio by looking.</p><p><strong>So the fleet size is arithmetic:</strong> 140 at peak, 200 per machine, plus one spare, equals <strong>two machines</strong>.</p><p>We were running five. We had been buying reassurance for about $180 a month and had never once checked the price.</p><p><strong>Cost per request.</strong> Total infrastructure divided by total requests came out at roughly <strong>$3.30 per million requests</strong>. That single number changed how we argued. “Should we cache this?” stopped being a matter of taste and became a sum.</p><p><strong>Targets we could defend.</strong> 99.9 percent availability, and the slowest one percent of feed loads under 300 milliseconds. Both derived from what we’d measured, rather than from what sounded impressive in a meeting.</p><p><strong>And the decision we deliberately did not make: we did not split the database.</strong> Splitting your data across multiple databases is the hardest decision to reverse in this entire article, because the rule you choose for <em>which data goes where</em> is extremely difficult to change once real data is spread across it. A bigger single database, plus a small piece of software in front to manage connections efficiently, carried us past a hundred thousand users with room to spare. The correct move was to not make that move yet.</p><h3>The Pattern</h3><p>Read back over the fixes and almost none of them are clever.</p><p>A number changed from 100 to 8. A missing word in a database command. One instruction to fetch related records together. A pinch of randomness on a cache lifetime. A check for whether a job had already run.</p><p>None of those are hard to write. <strong>What was hard was knowing which thing was broken.</strong></p><p>Every genuine fix in this log came from the same two steps, in the same order:</p><ol><li><strong>Measure the specific thing.</strong> Ask the database what it’s really doing. Count the queries one page makes. Push one machine until it breaks and note where. Clear the cache and watch what happens next.</li><li><strong>Change the specific thing</strong> — then measure again, to check you were right rather than lucky.</li></ol><p>Every failure we had was the inverse: something changed on a hunch, or nothing changed because nobody could see.</p><p>That’s a skill, and it’s a doing skill. You can read “beware of making one query per row” ten times and still ship it, because the bug is invisible on your own machine by design. You learn it properly once you’ve watched twenty-one queries scroll past where there should have been two.</p><h3>The course this came from</h3><p>I’ve built exactly this timeline into a course on <strong>Capstok</strong>, the learn-by-doing platform I’m working on: <a href="https://www.capstok.com/tracks/engineering/scaling-to-100k-users"><strong>Scaling to 100k Users: What Breaks Next and What to Fix</strong></a></p><p>Ten modules following this article’s milestones: Day 0, your first 100 users, your first 1,000, 10,000, moving slow work off the request path, running more than one machine, the database at scale, capacity and cost and on-call, deploys that don’t drop requests, and your first real incident.</p><p>Around a hundred tasks. Each one is a single concrete move with a runnable demo — Go, Python, Node and Rust where code matters — three levels of AI prompt to push further on anything that interests you, and a project at the end of every module. The capstones are the real artifacts: a 100k-user capacity plan with the arithmetic behind it, an on-call runbook pack, and a measured five-times latency improvement with the evidence attached.</p><p>It’s the half of this article I can’t write for you — the load test you run yourself, the stampede you cause on purpose, the knee you find on your own machine.</p><p><strong>It’s free to start right now. No card, nothing to cancel.</strong> We’re early and looking for product-market fit, which means I want your opinion considerably more than your money: what landed, what was too shallow, what you’d have written instead.</p><p>👉 <a href="https://www.capstok.com/tracks/engineering/scaling-to-100k-users"><strong>Start the course — free</strong></a></p><p><em>And a real question for the comments, because I’m collecting them: </em><strong><em>what broke first for you?</em></strong><em> Mine was a connection pool setting I copied from a blog post. I doubt I’m alone.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be11aa38610d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Tutorial to Production: How I Turned a 200-line URL Shortener into a Service I'd Actually…]]></title>
            <link>https://medium.com/@lklsquare/from-tutorial-to-production-how-i-turned-a-200-line-url-shortener-into-a-service-id-actually-c8cd135d70d1?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cd135d70d1</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sun, 03 May 2026 11:39:27 GMT</pubDate>
            <atom:updated>2026-05-03T11:47:40.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Tutorial to Production: How I Turned a 200-line URL Shortener into a Service I&#39;d Actually Deploy</h3><p><em>A walkthrough of every change that took a tutorial-grade Go service and made it pageable, scalable, and boring — in the best way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8_B18WV_SGNQvKUHK9HgA.jpeg" /></figure><blockquote>TL;DR</blockquote><blockquote>I turned a 200-line URL shortener into a production-grade Go service. The 19 things I had to add are universal — same checklist works for Node, Python, Java, Rust, anything. I packaged the whole audit as a language-agnostic skill called <strong>mjolnir</strong> that points an AI agent at any backend repo, walks the checklist, and renders a WORTHY / NOT WORTHY verdict with stack-specific recommendations for whatever&#39;s missing.</blockquote><blockquote><strong>Repo:</strong> <a href="https://github.com/lakshyakumar/mjolnir">github.com/lakshyakumar/mjolnir</a></blockquote><blockquote><strong>Install for Claude Code / Cowork:</strong></blockquote><blockquote>git clone https://github.com/lakshyakumar/mjolnir.git ~/.claude/skills/mjolnir</blockquote><blockquote>Restart your session, then ask any agent: <em>“audit this repo with mjolnir.”</em></blockquote><blockquote><strong>Use with any other agent (Cursor, Aider, Continue, your own):</strong> point it at the audit.md file in the repo — the instructions are written in generic verbs (<em>&quot;read the manifest file&quot;</em>, <em>&quot;search the source tree for…&quot;</em>) so any agent with file-read and search tools can execute it. Or just open checklist.md and walk it yourself; it&#39;s a normal markdown checklist.</blockquote><blockquote>If you’d rather see the full reasoning before reaching for the tool, read on.</blockquote><h3>The starting point</h3><p>A URL shortener is the “hello world” of backend interview prep. Take a long URL, return a short key, redirect on lookup. Two endpoints. A hash function. A map[string]string. You can write it in an afternoon.</p><p>I wrote that version. It worked. curl returned 301s. I felt clever for about ten minutes.</p><p>Then I asked myself an uncomfortable question: <strong>what would it actually take to deploy this?</strong> Not “what would impress an interviewer,” but what would I want in place before I let real traffic touch it, before I gave somebody else the pager, before I trusted it to not silently lose data on the third Tuesday of the month.</p><p>The answer turned out to be a checklist. Sixteen items. Most of them are not glamorous. None of them are optional.</p><p>This article is the diff between those two versions. The repo is <a href="https://github.com/lakshyakumar/production-ready-url-shortner-server">here</a> if you’d rather read code than prose.</p><h3>What “basic” looked like</h3><p>The starting service was about as bare as it gets:</p><ul><li>One main.go with handlers, business logic, and a SQL query mashed together.</li><li>A single *sql.DB passed around as a global.</li><li>No timeouts. Anywhere.</li><li>A log.Println here, a fmt.Printf there.</li><li>Errors returned as c.JSON(500, gin.H{&quot;error&quot;: err.Error()}) — leaking internals to the client and giving the client no stable code to match on.</li><li>Run with go run. Deploy by… well, I hadn&#39;t thought that far.</li></ul><p>It is a perfectly fine sketch. It is not a service.</p><h3>The changes, in the order I made them</h3><p>I’m going to walk through this in roughly the order I made the changes, because the order matters more than people admit. You can’t add tracing on top of a service that has no context discipline. You can’t add a circuit breaker if your DB calls aren’t going through a single seam. Each change unlocks the next.</p><h3>1. Layered architecture, with interfaces at the boundaries</h3><p>The first move was the most boring and the highest-leverage. I broke the monolithic main.go into layers:</p><pre>cmd/api/main.go              # composition root<br>internal/api/                # HTTP — Gin router, handlers, middleware<br>internal/service/            # business logic<br>internal/repository/         # SQL<br>internal/model/              # plain data<br>internal/platform/           # cross-cutting infra (db, redis, logger, observability)</pre><p>The trap I almost walked into: importing the database package from service, then noticing the breaker needed to log via slog, and then realizing slog needed config, and suddenly I had a circular import I couldn&#39;t unwind without a refactor.</p><p>The cure is a one-liner you’ll find in every clean-architecture book but rarely take seriously until it bites you: <strong>define interfaces where they’re consumed, not where they’re implemented.</strong></p><pre>// internal/repository/url_repo.go<br>type URLRepository interface {<br>    GetByShortKey(ctx context.Context, key string) (*model.URL, error)<br>    Create(ctx context.Context, u *model.URL) error<br>    // ...<br>}</pre><p>The service depends on repository.URLRepository. The implementation lives in the same package. The database package implements repository.Router — but repository doesn&#39;t import database. Imports flow one direction: cmd → api → service → repository → model, and platform/* is leaf-level infrastructure that satisfies interfaces from inner rings.</p><p>You don’t <em>feel</em> the value of this until you write your first unit test. Then you feel it forever.</p><h3>2. Context everywhere, with discipline</h3><p>Go’s context.Context is the single most important type in any production service, and it&#39;s the one most tutorials hand-wave away.</p><p>I added three rules and enforced them everywhere:</p><ol><li><strong>Every handler has a deadline.</strong> Not the request’s natural lifetime — an explicit one.</li></ol><pre>ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)<br>   defer cancel()</pre><ol><li><strong>Every DB call has a deadline.</strong></li></ol><pre>const dbCallTimeout = 5 * time.Second</pre><p>context.WithTimeout only <em>shortens</em> a deadline, so the handler&#39;s tighter ctx still wins when it should. 3. <strong>Detached background work uses a fresh context.</strong> When I needed to log a redirect <em>after</em> sending the response, I deliberately did not inherit the request context — it&#39;s already canceled by the time the goroutine runs:</p><pre>go func() {<br>       bgCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)<br>       defer cancel()<br>       repo.UpdateLastUsed(bgCtx, id)<br>   }()</pre><p>Context <strong>values</strong> got the same hygiene. No more c.Set(&quot;ip&quot;, ip) and c.Get(&quot;ip&quot;) with stringly-typed keys. Typed helpers, in one file:</p><pre>type contextKey string<br>const clientIPKey contextKey = &quot;client_ip&quot;<br><br>func WithClientIP(ctx context.Context, ip string) context.Context { ... }<br>func GetClientIP(ctx context.Context) string                       { ... }</pre><p>This sounds pedantic until two packages collide on &quot;user&quot; as a key in production and you spend an afternoon figuring out why.</p><h3>3. A real connection pool — with a circuit breaker</h3><p>The basic version called sql.Open and prayed. The production version uses pgx, two pools (primary + optional replica), and a circuit breaker on each pool.</p><pre>// router.go<br>func (r *poolRouter) Reader() repository.DBTX {<br>    if r.replica != nil &amp;&amp; r.replica.cb.State() != gobreaker.StateOpen {<br>        return r.replica<br>    }<br>    return r.primary<br>}</pre><p>The interesting part isn’t the breaker library. It’s deciding <strong>which errors should count as failures</strong>. A unique_violation is the caller&#39;s fault, not the database&#39;s — counting it would trip the breaker on perfectly healthy traffic. A connection refused is real. A context cancellation from a client who hung up is neither.</p><p>I ended up classifying by SQLSTATE prefix:</p><pre>func shouldCount(err error) bool {<br>    if err == nil { return false }<br>    if errors.Is(err, repository.ErrNotFound) { return false }<br>    if errors.Is(err, context.Canceled)       { return false }<br>    if errors.Is(err, context.DeadlineExceeded) { return true }<br>    var pgErr *pgconn.PgError<br>    if errors.As(err, &amp;pgErr) {<br>        switch pgErr.Code[:2] {<br>        case &quot;23&quot;, &quot;42&quot;: return false                     // constraint / syntax<br>        case &quot;53&quot;, &quot;57&quot;, &quot;58&quot;, &quot;08&quot;, &quot;XX&quot;: return true    // resource / system<br>        }<br>    }<br>    return true<br>}</pre><p>This is the kind of code that looks trivial in a blog post and saves your weekend in production.</p><h3>4. Distributed rate limiting via Redis</h3><p>In-process rate limiting is a lie if you ever run more than one replica — and you will. The basic version had a golang.org/x/time/rate limiter per process. Behind a load balancer with three replicas, that&#39;s a 3× quota. Behind ten replicas, 10×.</p><p>The fix: Redis fixed-window counters keyed by client IP.</p><pre>INCR rl:&lt;ip&gt;:&lt;window_bucket&gt;<br>EXPIRE rl:&lt;ip&gt;:&lt;window_bucket&gt; &lt;window_seconds&gt;   # only on first hit</pre><p>Every replica hits the same Redis. The cap holds regardless of replica count. Two more decisions paid off later:</p><ul><li><strong>Bounded Redis timeout.</strong> A 100ms RedisOpTimeout per call, so a Redis blip doesn&#39;t cascade into API latency.</li><li><strong>Fail-open.</strong> If Redis is unreachable, the limiter logs a warning and lets the request through. Availability of the API beats strict rate limiting during a Redis incident. Whether you agree depends on your threat model — but make the choice consciously, don’t let it be an accident of how if err != nil falls.</li></ul><h3>5. Leader election for the cleanup cron</h3><p>The shortener has a cleanup job that purges URLs unused beyond a threshold. With one replica, you call it from a time.Ticker. With many replicas, every replica fires the ticker, and you race to delete the same rows.</p><p>You don’t need ZooKeeper for this. You need pg_try_advisory_lock:</p><pre>func (l *Locker) Run(ctx context.Context, key int64, fn func(context.Context) error) error {<br>    conn, _ := l.pool.Acquire(ctx); defer conn.Release()<br>    var got bool<br>    _ = conn.QueryRow(ctx, &quot;SELECT pg_try_advisory_lock($1)&quot;, key).Scan(&amp;got)<br>    if !got { return nil }<br>    defer conn.Exec(context.Background(), &quot;SELECT pg_advisory_unlock($1)&quot;, key)<br>    return fn(ctx)<br>}</pre><p>Every replica’s ticker fires. Exactly one wins the lock per tick. The lock is session-scoped — if the leader crashes, Postgres releases it on connection close. No stuck-leader scenario, even on kill -9.</p><p>I love this primitive. It’s free, it ships with a database I already trust, and it’s six lines of code.</p><h3>6. The full observability triangle</h3><p>Logs, traces, metrics. They answer different questions, and once I’d wired them up I never wanted to write a service without them again.</p><p><strong>slog for &quot;what happened.&quot;</strong> Stdlib, JSON to stdout, slog.InfoContext(ctx, ...) so the request context flows. Every fmt.Printf and log.Println got deleted with prejudice.</p><p><strong>OpenTelemetry for “where was time spent.”</strong> The trick I’m proudest of here: tracing is <em>optional but always wired</em>. If OtelExporterEndpoint is empty, a no-op TracerProvider is installed:</p><pre>if cfg.ExporterEndpoint == &quot;&quot; {<br>    otel.SetTracerProvider(noop.NewTracerProvider())<br>    return func(context.Context) error { return nil }, nil<br>}</pre><p>That means otelgin, otelpgx, and redisotel are <em>always</em> in the request path — no if cfg.TracingEnabled branches anywhere — they just become near-zero-cost calls when no exporter is configured. Dev environments don&#39;t need a collector. Prod just sets the env var.</p><p><strong>Prometheus for “is anything trending the wrong way.”</strong> A custom prometheus.Registry (not the global default), HTTP RED metrics, rate-limit decisions, Go runtime collectors. The discipline that matters: <strong>bounded cardinality.</strong> The route label is always the Gin route template (/:key, /shorten) — never the raw URL. Otherwise your metrics backend dies and takes your wallet with it.</p><h3>7. pprof, on a private port</h3><p>_ &quot;net/http/pprof&quot; is one line. The catch is that the default registration puts it on http.DefaultServeMux, which is also where most people serve their API. That&#39;s a security incident waiting to happen — /debug/pprof/profile?seconds=300 will pin a CPU and leak symbol tables to anyone who can reach it.</p><p>The fix: a <em>separate</em> HTTP server on a private port, hosting both pprof and /metrics:</p><pre>debugMux := http.NewServeMux()<br>debugMux.Handle(&quot;/debug/pprof/&quot;, http.DefaultServeMux)  // pprof registers on the default mux<br>debugMux.Handle(&quot;/metrics&quot;, observability.Handler(metricsReg))</pre><p>Two surfaces, one firewall rule. Plus runtime.SetBlockProfileRate(1) and runtime.SetMutexProfileFraction(1) at startup so block and mutex profiles return data without extra setup.</p><h3>8. Graceful shutdown, in the right order</h3><p>This is the one almost every basic service gets wrong. You catch a SIGTERM, you call srv.Shutdown(ctx), you call it a day. Then you discover that:</p><ul><li>Your last requests’ traces never made it to the exporter, because you closed the tracer before the in-flight requests finished.</li><li>Your DB pool closed while a goroutine was still using it, panicking the binary.</li><li>A second Ctrl+C aborted the drain on the first one, killing requests mid-flight.</li></ul><p>The right order is the <strong>inverse of startup</strong>, with a <em>detached</em> shutdown context:</p><pre>shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)<br>defer cancel()<br><br>srv.Shutdown(shutdownCtx)        // 1. drain HTTP — handlers complete spans<br>tracerShutdown(shutdownCtx)      // 2. flush spans — last requests get exported<br>debugSrv.Shutdown(shutdownCtx)   // 3. close /debug/pprof and /metrics<br>// 4. defers run in LIFO: redisClient.Close() → db pool close</pre><p>Detached from rootCtx, so a second Ctrl+C cancels the second wait — not the drain.</p><h3>9. Distroless multistage Docker</h3><p>The basic version’s Dockerfile was FROM golang:latest. 1.2 GB. Full shell. Root user. Apt sitting there waiting to install whatever a compromised process wants.</p><p>The production version is a two-stage build:</p><pre># Dockerfile<br>FROM golang:1.26.1-alpine AS builder<br># module + build caches via --mount=type=cache<br>RUN CGO_ENABLED=0 go build -trimpath -ldflags=&quot;-s -w&quot; -o /out/url-shortener ./cmd/api<br><br>FROM gcr.io/distroless/static-debian12:nonroot<br>COPY --from=builder /out/url-shortener /url-shortener<br>USER nonroot:nonroot<br>ENTRYPOINT [&quot;/url-shortener&quot;]</pre><p>~15 MB final image. No shell, no package manager, no glibc, runs as UID 65532. If an attacker pops the binary, they get the binary. Not bash. Not apt. Not curl. The binary.</p><h3>10. CI that fails for the same reasons locally and remotely</h3><p>A pre-commit hook that runs the same six stages as GitHub Actions: gofmt, swag (for Swagger annotations), go vet, golangci-lint, go build, make test-coverage. Coverage has a floor (60%, ratcheting up); below it the build fails.</p><p>The thing that surprised me most: <strong>a coverage gate is more useful for what it forces you to <em>not</em> do</strong> than what it forces you to do. It quietly kills “I’ll add tests later” PRs.</p><p>CI also builds the Docker image on every push and pushes vX.Y.Z + latest to GHCR on tag pushes. The docker-build job has needs: lint+test, so an image whose tests just failed never reaches the registry.</p><h3>11. Health probes, fuzzers, benchmarks, migrations</h3><p>A grab-bag of small things, each one a few hours of work, each one paying back forever:</p><ul><li><strong>/liveness and </strong><strong>/readiness</strong> — Kubernetes-shaped probes. Liveness always 200, readiness pings the DB with a 2s timeout. Both bypass the rate limiter so probes don&#39;t burn quota.</li><li><strong>A fuzzer for the short-key generator</strong> (make test-fuzz). Failing inputs auto-save into testdata/fuzz/..., so they become regression tests forever after.</li><li><strong>Benchmarks</strong> for the same generator (make test-bench), so a refactor that quietly made it 4× slower fails the next CI run.</li><li><strong>golang-migrate</strong> for schema, with up/down pairs. Compose runs migrations as a one-shot service before the API starts. No &quot;I&#39;ll just run the SQL by hand&quot; — that&#39;s how you get a dirty schema version: true at 3 AM.</li></ul><h3>What it actually feels like</h3><p>Here is the part nobody writes: this stuff is <em>less</em> fun to code than the toy version. Building the shortener was a Saturday afternoon. Building everything around the shortener took weeks of evenings.</p><p>But the resulting service has a quality the toy version didn’t have, and the word for it is <strong>boring</strong>. I can run multiple replicas and the rate limiter still works. I can kubectl rollout restart and not lose requests. I can SSH into a problem and have traces, metrics, logs, and a flame graph waiting. I can add a test and the coverage gate tells me whether I just made things better or worse.</p><p>The basic version was 200 lines and impressive to a junior engineer. The production version is 5,000 lines and impressive to nobody — until it’s the one that’s still up at 3 AM.</p><p>That’s the trade. That’s the article.</p><h3>The checklist, one more time</h3><p>If you’re staring at a service of your own and wondering where to start, this is the order I’d do it in. Each one unlocks the next:</p><ol><li>Layered architecture with interfaces at the boundaries</li><li>Context discipline — timeouts, typed values, no string keys</li><li>A real connection pool with a circuit breaker</li><li>Distributed rate limiting (Redis or equivalent)</li><li>Leader election for periodic work (pg_try_advisory_lock is plenty)</li><li>OpenTelemetry tracing — wired always-on, exporter optional</li><li>Prometheus metrics — own registry, bounded cardinality</li><li>Structured logging via slog</li><li>pprof on a private debug port</li><li>Graceful shutdown in inverse-startup order, with a detached context</li><li>Distroless multistage Docker, nonroot, static binary</li><li>CI with a pre-commit hook that mirrors it exactly</li><li>Coverage gate, fuzz, benchmarks</li><li>Liveness + readiness probes</li><li>Schema migrations via a real tool, run as a one-shot before the API</li><li>A README that maps every one of these to the file that implements it</li></ol><p>Code is at <a href="https://github.com/lakshyakumar/production-ready-url-shortner-server">github.com/lakshyakumar/production-ready-url-shortner-server</a>. The README walks each step with file links and snippets. Steal whatever’s useful.</p><p>If there’s a section you want me to go deeper on — the breaker error classification, the always-on noop tracer, the leader lock — let me know and I’ll write that one next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cd135d70d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering GitFlow: A Production-Ready Branching Strategy for Enterprise Development Teams]]></title>
            <link>https://medium.com/@lklsquare/mastering-gitflow-a-production-ready-branching-strategy-for-enterprise-development-teams-fa2e56377094?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2e56377094</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Tue, 16 Sep 2025 10:01:06 GMT</pubDate>
            <atom:updated>2025-09-16T10:01:06.344Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to implement a robust Git workflow that scales from feature development to hotfix deployments</em></p><p>Modern software development demands a branching strategy that can handle parallel feature development, stable releases, and emergency hotfixes without breaking production. Enter GitFlow — a time-tested approach that brings order to the chaos of multi-developer, multi-version codebases.</p><p>In this comprehensive guide, we’ll walk through implementing a GitFlow-based branching strategy that’s battle-tested in production environments. You’ll learn not just the <em>what</em>, but the <em>how</em> and <em>when</em> of each Git operation.</p><h3>The Anatomy of GitFlow: Understanding Branch Hierarchies</h3><p>GitFlow organizes your repository around five core branch types, each serving a specific purpose in your development lifecycle:</p><h3>Branch Architecture Overview</h3><pre>feature/JIRA-123 ──┐<br>feature/JIRA-456 ──┤<br>                   ├──► develop ──► release/1.2 ──► main<br>                   │                    ▲<br>hotfix/JIRA-789 ───┘                    │<br>                                        │<br>                              (backport fixes)</pre><p><strong>Feature Branches: </strong><strong>feature/&lt;JIRA-ID&gt;</strong></p><ul><li>Isolated development environments for new features</li><li>Branch off from develop</li><li>Merge back into develop via Pull Request</li></ul><p><strong>Release Branches: </strong><strong>release/X.Y</strong></p><ul><li>Stabilization branches for upcoming releases</li><li>Created from develop when feature-complete</li><li>Allow bug fixes while new features continue in develop</li></ul><p><strong>Hotfix Branches: </strong><strong>hotfix/&lt;JIRA-ID&gt;</strong></p><ul><li>Emergency fixes for production issues</li><li>Branch off from latest release branch or main</li><li>Merged into main, develop, and current release branch</li></ul><p><strong>Core Branches:</strong></p><ul><li>main: Production-ready code, tagged releases</li><li>develop: Integration branch for features</li></ul><h3>Implementing GitFlow: The Complete Workflow</h3><p>Let’s walk through the entire process from feature development to production deployment.</p><h3>Phase 1: Feature Development</h3><p>Every new feature starts with a dedicated branch:</p><pre># Start from the latest develop branch<br>git checkout develop<br>git pull origin develop<br><br># Create your feature branch<br>git checkout -b feature/JIRA-456<br><br># Develop your feature with atomic commits<br>git add .<br>git commit -m &quot;feat(JIRA-456): implement user authentication module&quot;<br><br># Push feature branch for collaboration<br>git push origin feature/JIRA-456</pre><p><strong>Pro tip</strong>: Use conventional commit messages (feat:, fix:, docs:, bug:) for better changelog generation.</p><h3>Phase 2: Feature Integration</h3><p>Once your feature is complete, integrate it back into the development stream:</p><pre># Keep your branch current with develop<br>git checkout develop<br>git pull origin develop<br>git checkout feature/JIRA-456<br>git rebase develop<br><br># Push updated feature branch<br>git push origin feature/JIRA-456</pre><p>Create a Pull Request from feature/JIRA-456 → develop. After code review and CI passes, merge using the &quot;Squash and merge&quot; strategy to keep develop history clean.</p><h3>Phase 3: Release Preparation</h3><p>When develop contains all features for the next release, create a release branch:</p><pre># Create release branch from develop<br>git checkout develop<br>git pull origin develop<br>git checkout -b release/1.2<br>git push origin release/1.2</pre><p>During release stabilization, only bug fixes are allowed:</p><pre># Fix bugs discovered during testing<br>git checkout release/1.2<br>git add .<br>git commit -m &quot;fix(release): resolve authentication timeout issue&quot;<br>git push origin release/1.2</pre><h3>Phase 4: Production Deployment</h3><p>Once the release is stable, promote it to production:</p><pre># Merge release to main<br>git checkout main<br>git pull origin main<br>git merge --no-ff release/1.2<br>git push origin main<br><br># Tag the release<br>git tag -a v1.2.0 -m &quot;Release version 1.2.0&quot;<br>git push origin v1.2.0<br><br># Backport release fixes to develop<br>git checkout develop<br>git merge --no-ff release/1.2<br>git push origin develop</pre><p>The --no-ff flag ensures merge commits are created, preserving branch history for better traceability.</p><h3>GitHub Actions Integration: Automating the Pipeline</h3><p>Here’s a production-ready CI/CD pipeline that works seamlessly with GitFlow:</p><pre>name: GitFlow CI/CD Pipeline<br>on:<br>  push:<br>    branches: [ develop, main, &#39;release/*&#39; ]<br>  pull_request:<br>    branches: [ develop ]<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Run tests<br>        run: |<br>          npm ci<br>          npm run test:coverage<br>          <br>  deploy-staging:<br>    needs: test<br>    if: github.ref == &#39;refs/heads/develop&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Deploy to staging<br>        run: echo &quot;Deploying develop to staging environment&quot;<br>        <br>  deploy-production:<br>    needs: test<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Deploy to production<br>        run: echo &quot;Deploying main to production environment&quot;</pre><h3>Emergency Response: Hotfix Procedures</h3><p>When production breaks, speed matters. Here’s how to deploy emergency fixes:</p><pre># Create hotfix from current release or main<br>git checkout release/1.2  # or main if no current release branch<br>git pull origin release/1.2<br>git checkout -b hotfix/JIRA-789<br><br># Implement the critical fix<br>git add .<br>git commit -m &quot;fix(critical): resolve payment processing bug&quot;<br>git push origin hotfix/JIRA-789</pre><p>Deploy the hotfix to all relevant branches:</p><pre># Merge to main (production)<br>git checkout main<br>git merge --no-ff hotfix/JIRA-789<br>git push origin main<br>git tag -a v1.2.1 -m &quot;Hotfix release 1.2.1&quot;<br><br># Backport to develop<br>git checkout develop<br>git merge --no-ff hotfix/JIRA-789<br>git push origin develop<br><br># Update current release branch if exists<br>git checkout release/1.2<br>git merge --no-ff hotfix/JIRA-789<br>git push origin release/1.2</pre><h3>Rollback Strategies: When Things Go Wrong</h3><p>Sometimes you need to quickly revert a problematic release:</p><h3>Option 1: Hard Reset (Destructive)</h3><p>bash</p><pre>git checkout main<br>git reset --hard &lt;previous-release-commit&gt;<br>git push --force origin main</pre><p><strong>⚠️ Warning</strong>: This rewrites history. Only use in emergency situations and coordinate with your team.</p><h3>Option 2: Revert Commit (Safer)</h3><p>bash</p><pre>git checkout main<br>git revert -m 1 &lt;merge-commit-hash&gt;<br>git push origin main</pre><p>This creates a new commit that undoes the changes, preserving history.</p><h3>The Trade-offs: When GitFlow Shines (and When It Doesn’t)</h3><h3>✅ GitFlow Excels When:</h3><ul><li><strong>Multiple release versions</strong>: Supporting v1.x and v2.x simultaneously</li><li><strong>Scheduled releases</strong>: Monthly or quarterly release cycles</li><li><strong>Large teams</strong>: 10+ developers working on different features</li><li><strong>Enterprise environments</strong>: Where stability trumps speed</li><li><strong>Complex testing cycles</strong>: Extended QA and UAT phases</li></ul><h3>❌ Consider Alternatives When:</h3><ul><li><strong>Continuous deployment</strong>: Deploying multiple times daily</li><li><strong>Small teams</strong>: 2–5 developers who can coordinate easily</li><li><strong>Simple products</strong>: Single-version SaaS applications</li><li><strong>Fast iteration</strong>: Startup environments prioritizing speed</li></ul><h3>Maintenance Overhead Reality Check</h3><p>GitFlow requires discipline. You’ll be managing:</p><ul><li>2–3 long-lived branches (main, develop, current release/*)</li><li>Multiple feature branches in parallel</li><li>Hotfix coordination across branches</li><li>Merge conflict resolution</li></ul><p>Budget 10–15% additional time for branch management activities.</p><h3>Project Suitability Matrix</h3><pre>| Project Type | Team Size | Release Cycle | GitFlow Fit |<br>|--------------|-----------|---------------|-------------|<br>| Enterprise Software | 10-50+ | Quarterly | ⭐⭐⭐⭐⭐ |<br>| SaaS Platform | 5-15 | Monthly | ⭐⭐⭐⭐ |<br>| Open Source | Variable | Variable | ⭐⭐⭐⭐ |<br>| Mobile Apps | 3-8 | Bi-weekly | ⭐⭐⭐ |<br>| Microservices | 2-5 per service | Continuous | ⭐⭐ |</pre><h3>Essential Rules and Conventions</h3><p>To make GitFlow work effectively, establish these non-negotiable rules:</p><h3>Branch Protection Rules</h3><ol><li><strong>No direct pushes to </strong><strong>main or </strong><strong>develop</strong></li><li><strong>All features via Pull Request</strong></li><li><strong>Require CI passing + code review</strong></li><li><strong>Enforce linear history on main</strong></li></ol><h3>Naming Conventions</h3><pre>feature/JIRA-123-user-authentication<br>release/2.1<br>hotfix/JIRA-456-payment-fix</pre><h3>Commit Message Standards</h3><pre>feat(auth): implement OAuth2 integration<br>fix(payment): resolve timeout in checkout flow<br>docs(readme): update GitFlow procedures</pre><h3>Tagging Strategy</h3><pre>v1.0.0    # Major release<br>v1.0.1    # Hotfix<br>v1.1.0    # Minor release<br>v2.0.0    # Major breaking changes</pre><h3>Making GitFlow Work: Advanced Tips</h3><h3>1. Automate Branch Cleanup</h3><pre># Delete merged feature branches<br>git branch --merged develop | grep -v develop | xargs git branch -d</pre><h3>2. Use Git Hooks for Validation</h3><p>Create .git/hooks/pre-commit to enforce standards:</p><pre>#!/bin/sh<br>npm run lint &amp;&amp; npm run test:fast</pre><h3>3. Implement Branch Policies</h3><p>Configure your Git hosting platform to enforce:</p><ul><li>Required status checks</li><li>Up-to-date branch requirements</li><li>Administrator enforcement</li></ul><h3>4. Monitor Branch Age</h3><p>Set up alerts for feature branches older than 2 weeks to prevent integration hell.</p><h3>Conclusion: GitFlow as Your Development Backbone</h3><p>GitFlow isn’t just a branching strategy — it’s a framework for scaling development teams while maintaining code quality and release predictability. The upfront investment in process discipline pays dividends as your team and codebase grow.</p><p>The key to success lies not in rigid adherence to every GitFlow principle, but in adapting its core concepts to your team’s specific needs. Start with the basic feature → develop → release → main flow, then add complexity as your processes mature.</p><p>Remember: the best branching strategy is the one your entire team understands and follows consistently. GitFlow provides that common language for development teams ready to level up their release management game.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2e56377094" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching AI to Remember: A Guide for Forgetful Bots]]></title>
            <link>https://medium.com/@lklsquare/teaching-ai-to-remember-a-guide-for-forgetful-bots-4eb1be64e26c?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb1be64e26c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 13:16:23 GMT</pubDate>
            <atom:updated>2025-07-18T13:16:23.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Episodic, Semantic &amp; Procedural Memory in AI</h3><h3>✅ TL;DR Summary</h3><blockquote><em>🧠 LLM agents are getting smarter — but real intelligence needs memory. Just like humans, LLMs can benefit from:</em></blockquote><ul><li><strong>Semantic Memory</strong> (encyclopedia of facts)</li><li><strong>Episodic Memory</strong> (remembering past interactions)</li><li><strong>Procedural Memory</strong> (knowing how to do things)</li></ul><blockquote><em>This trio helps agents become more helpful, consistent, and personal. Learn how to implement each and what it means for building the future of AI agents.</em></blockquote><blockquote>Imagine talking to someone who forgets everything you just said, can’t recall facts about the world, and doesn’t know how to follow instructions.</blockquote><blockquote>Now imagine that person is your AI assistant.</blockquote><blockquote>Not great, right?</blockquote><p>Today’s AI agents powered by <strong>Large Language Models (LLMs)</strong> are getting smarter by the day. But one missing piece keeps holding them back: <strong>memory</strong>.</p><p>In this article, we’ll explore how LLMs can develop a mind more like ours by mimicking three types of human memory:</p><ul><li>🧠 <strong>Semantic Memory</strong> — What we know</li><li>📘 <strong>Episodic Memory</strong> — What we’ve experienced</li><li>⚙️ <strong>Procedural Memory</strong> — What we’ve learned how to do</li></ul><p>Let’s dive in — through analogies, technical insights, and real-world applications.</p><h3>🧠 “The Encyclopedia in the Brain”</h3><h3>Semantic Memory: What the Agent Knows</h3><h4>📖 Analogy:</h4><p>Think of semantic memory as a <strong>mental encyclopedia</strong>.<br> It’s how you know that water boils at 100°C, Paris is the capital of France, and GPT stands for Generative Pretrained Transformer.</p><p>An AI with semantic memory is like someone who <strong>read a million books and never forgot a single fact</strong>.</p><h4>💡 Why It Matters:</h4><p>LLMs rely on this memory to answer factual questions, understand language, and provide expert knowledge across domains — from medicine to finance to poetry.</p><h4>🛠 How It’s Implemented:</h4><ul><li><strong>Pretrained model weights</strong>: LLMs are trained on billions of text tokens — this is their core semantic memory.</li><li><strong>Retrieval-Augmented Generation (RAG)</strong>: When knowledge needs to be fresher or more domain-specific, agents “look up” facts from vector stores and documents.</li><li><strong>Knowledge bases or APIs</strong>: Structured semantic memory like company databases or product catalogs.</li></ul><h4>🧑‍💻 For Builders:</h4><p>Use tools like <strong>LangChain</strong> or <strong>LlamaIndex</strong> to pipe in external knowledge as dynamic semantic memory.</p><h3>📘 “The Scrapbook of Experiences”</h3><h3>Episodic Memory: What the Agent Remembers Happening</h3><h4>🪞 Analogy:</h4><p>Episodic memory is like a <strong>scrapbook or diary</strong>. It captures personal experiences:</p><ul><li>That time you asked your assistant to summarize a 10-page PDF.</li><li>The fact that you like your reports in Markdown.</li><li>The last conversation you had about climate tech startups.</li></ul><p>An AI without episodic memory is like a goldfish — <strong>every interaction is Day One</strong>.</p><h4>💡 Why It Matters:</h4><p>With episodic memory, LLM agents can build relationships, remember preferences, track context across sessions, and work on long-term goals.</p><h4>🛠 How It’s Implemented:</h4><ul><li><strong>Temporary memory</strong>: Context window holds recent conversation (until it overflows).</li><li><strong>Long-term memory</strong>: External stores (like a vector database) keep embeddings of past chats, organized by user, time, or topic.</li><li><strong>Retrieval logic</strong>: Past memories are searched and injected when relevant.</li></ul><h4>🧑‍💻 For Builders:</h4><p>Use embedding models like sentence-transformers, and tools like <strong>Pinecone</strong> or <strong>Weaviate</strong> to store and retrieve episodic memory by relevance.</p><h3>⚙️ “The Recipe Book in the Mind”</h3><h3>Procedural Memory: What the Agent Knows How to Do</h3><h4>🍳 Analogy:</h4><p>Procedural memory is like your brain’s <strong>recipe book or muscle memory</strong>.</p><p>You don’t have to <em>think</em> about how to tie your shoelaces or ride a bike — you just do it.</p><p>For an LLM agent, procedural memory is what allows it to:</p><ul><li>Follow instructions</li><li>Execute workflows</li><li>Maintain formatting or tone</li><li>Decide what action to take next</li></ul><p>It’s not about <em>what</em> or <em>when</em> — it’s about <strong>how</strong>.</p><h4>💡 Why It Matters:</h4><p>Agents need this to be useful. Whether writing SQL queries, conducting research, or onboarding users — <strong>instructions are their playbook</strong>.</p><h4>🛠 How It’s Implemented:</h4><ul><li><strong>Prompt engineering</strong>: Core instructions are embedded in the system prompt (e.g., “You are an AI assistant who always responds formally.”)</li><li><strong>Reusable flows</strong>: Prompt templates, YAML-based instruction trees, or agent graphs define behavior.</li><li><strong>Task automation</strong>: Agents like LangGraph, AutoGen, or CrewAI allow you to define procedural logic, decision paths, and actions.</li></ul><h4>🧑‍💻 For Builders:</h4><p>Procedural memory often lives in:</p><ul><li>Prompt templates (prompt.txt, prompt.json)</li><li>Agent graphs (like finite state machines)</li><li>Embedded instructions dynamically injected at runtime</li></ul><h3>🧠 Putting It All Together</h3><h3>Building Agents with Human-Like Minds</h3><p>Here’s how these three memory types work in concert:</p><p><strong>🧠 Semantic Memory</strong></p><ul><li><strong>What it remembers:</strong> Facts &amp; general knowledge</li><li><strong>Analogy:</strong> Like an encyclopedia or Wikipedia</li><li><strong>Example:</strong> “Paris is in France”</li></ul><p><strong>📘 Episodic Memory</strong></p><ul><li><strong>What it remembers:</strong> Personal experiences and past interactions</li><li><strong>Analogy:</strong> Like a diary or photo album</li><li><strong>Example:</strong> “You asked for dark mode last week”</li></ul><p><strong>⚙️ Procedural Memory</strong></p><ul><li><strong>What it remembers:</strong> How-tos, workflows, and task instructions</li><li><strong>Analogy:</strong> Like a recipe book or user manual</li><li><strong>Example:</strong> “Respond using JSON structure”</li></ul><p>A great agent <strong>knows</strong>, <strong>remembers</strong>, and <strong>does</strong>.</p><h3>🚧 Still Figuring It Out</h3><h3>Challenges in AI Memory</h3><p>Memory isn’t all sunshine and context tokens. Building memory-aware LLMs comes with a few growing pains:</p><ul><li><strong>Memory overflow</strong>: Prompt windows are limited — agents forget unless you store things smartly.</li><li><strong>What to forget</strong>: If everything is saved, performance slows. If too much is deleted, the agent becomes clueless.</li><li><strong>Agent hallucinations</strong>: Sometimes, memory retrieval can make things worse if irrelevant or noisy data is injected.</li><li><strong>Privacy concerns</strong>: Long-term memory requires care in data governance and compliance.</li></ul><h3>🚀 Agents That Grow With You</h3><p>Imagine AI agents that evolve as they interact with you:</p><ul><li>They learn your style, your workflow, your quirks.</li><li>They remember conversations from a month ago.</li><li>They follow your unique process for building reports, onboarding clients, or analyzing markets.</li></ul><p>That’s the power of semantic, episodic, and procedural memory — <strong>turning static chatbots into dynamic AI companions</strong>.</p><blockquote>“Memory is the treasure house of the mind.” — Thomas Fuller</blockquote><p>The future of AI lies not in bigger models, but <strong>smarter memories</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb1be64e26c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Vector Search in MongoDB: Best Practices for Real-Time Semantic Retrieval]]></title>
            <link>https://medium.com/@lklsquare/vector-search-in-mongodb-best-practices-for-real-time-semantic-retrieval-a8186c6df852?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8186c6df852</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 03:20:02 GMT</pubDate>
            <atom:updated>2025-07-02T03:20:02.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔍 Why Vector Search?</h3><p>Imagine building a movie app where users type:</p><blockquote><em>“A thought-provoking sci-fi film about human survival on a lonely planet.”</em></blockquote><p>Traditional search engines might return something irrelevant, unless those exact words exist in the synopsis.</p><p><strong>Vector search</strong>, on the other hand, understands the meaning behind the query and surfaces semantically similar results like:</p><ul><li><em>The Martian</em></li><li><em>Interstellar</em></li><li><em>Moon</em></li></ul><p>MongoDB Atlas now supports vector search — so let’s explore the <strong>best practices</strong> to make it fast, accurate, and scalable.</p><h3>🔁 ANN vs 🧪 ENN: Which Should You Use?</h3><h3>🔁 Approximate Nearest Neighbor (ANN)</h3><ul><li>✅ Best for large datasets and real-time applications</li><li>⚡ Faster and more scalable</li><li>🧠 Uses HNSW indexing under the hood</li><li>🎯 Great balance of speed and quality</li><li>✔ Default in MongoDB (no extra config needed)</li></ul><h3>🧪 Exact Nearest Neighbor (ENN)</h3><ul><li>✅ Guaranteed perfect recall</li><li>🐢 Slower and memory-heavy</li><li>🧪 Useful for small datasets, validation, or debugging</li><li>❗ Use exact: true to enable it explicitly</li></ul><h3>🧠 Similarity Metrics: Choose the Right One</h3><h3>🧭 Cosine Similarity</h3><ul><li>Measures angle between vectors (not magnitude)</li><li>✅ Perfect for text embeddings (OpenAI, BERT, Cohere)</li><li>🔍 Focuses on meaning, not scale</li><li>📌 <strong>Recommended for most NLP tasks</strong></li></ul><h3>📐 Dot Product</h3><ul><li>Considers both direction and length</li><li>✅ Ideal for weighted embeddings or learned representations</li><li>⚠️ May favor longer vectors if not normalized</li></ul><h3>📏 Euclidean Distance</h3><ul><li>Pure distance in space (like measuring with a ruler)</li><li>📸 Better for visual or geometric data</li><li>❗ Sensitive to vector scaling</li></ul><p>📘 Use this in your $vectorSearch:</p><pre>similarity: &quot;cosine&quot; // or &quot;dotProduct&quot;, &quot;euclidean&quot;</pre><h3>📦 Quantization: Make It Lighter and Faster</h3><h3>🔢 Scalar Quantization (int8)</h3><ul><li>~4x smaller than float32</li><li>✅ Good trade-off between accuracy and speed</li><li>✅ Great for 100K–10M vectors</li><li>Easy to enable at index creation</li></ul><h3>⚫ Binary Quantization (int1)</h3><ul><li>~24x smaller!</li><li>🏁 Ideal for ultra-large-scale datasets</li><li>⚠️ Requires rescoring after search to ensure accuracy</li><li>Best used with massive vector stores</li></ul><p>🛠 Enable it like this:</p><pre>&quot;quantization&quot;: &quot;int8&quot; // or &quot;int1&quot;</pre><h3>🎯 Tune Your Parameters: limit and numCandidates</h3><h3>📉 limit</h3><ul><li>Controls how many results are returned</li><li>e.g., limit: 5 means top 5 most relevant results</li></ul><h3>📊 numCandidates</h3><ul><li>Determines how many vectors are considered before scoring</li><li>Higher = better recall, slower speed</li><li>🔁 Rule of thumb: numCandidates ≈ 20 × limit</li></ul><p>🛠 Example:</p><pre>{<br>  limit: 5,<br>  numCandidates: 100<br>}</pre><h3>⚙️ Pre-Filtering vs Post-Filtering</h3><h3>✅ Pre-Filtering</h3><ul><li>Filters applied <em>before</em> similarity scoring</li><li>🔥 Great for narrowing search space and improving performance</li><li>Works on fields like genre, tags, or date range</li></ul><pre>filter: {<br>  genre: &quot;Sci-Fi&quot;,<br>  year: { $gte: 2010 }<br>}</pre><h3>⚠️ Post-Filtering</h3><ul><li>Filters applied <em>after</em> the vector search</li><li>Use for computed, fuzzy, or complex fields</li><li>⏳ Slower and less efficient — only use when necessary</li></ul><h3>🧮 Dimensionality: Keep It Reasonable</h3><ul><li>✅ Common choices: 384, 512, or 768 dimensions</li><li>❌ Avoid using 1000+ dims unless absolutely necessary</li><li>Use dimensionality reduction (PCA or UMAP) if embeddings are too large</li></ul><h3>🧊 Store Vectors as binData for Speed</h3><p>MongoDB stores vectors using binary format for better speed and memory efficiency.</p><p>✅ Good:</p><pre>&quot;embedding&quot;: {<br>  &quot;$binary&quot;: {<br>    &quot;base64&quot;: &quot;...&quot;,<br>    &quot;subType&quot;: &quot;00&quot;<br>  }<br>}</pre><p>Avoid using raw arrays like [0.23, 0.48, ...] in production—convert them.</p><h3>🔬 Example: Movie Recommendation Search</h3><pre>db.movies.aggregate([<br>  {<br>    $vectorSearch: {<br>      index: &quot;movieVecIdx&quot;,<br>      path: &quot;embedding&quot;,<br>      queryVector: [/* user vector */],<br>      similarity: &quot;cosine&quot;,<br>      filter: {<br>        genre: &quot;Sci-Fi&quot;,<br>        year: { $gte: 2010 }<br>      },<br>      numCandidates: 100,<br>      limit: 5<br>    }<br>  },<br>  {<br>    $project: {<br>      title: 1,<br>      year: 1,<br>      genre: 1,<br>      similarityScore: { $meta: &quot;vectorSearchScore&quot; }<br>    }<br>  }<br>]);</pre><h3>📌 MongoDB Vector Search Best Practices Summary</h3><ul><li>✅ Use <strong>ANN</strong> for real-time search, <strong>ENN</strong> only when needed</li><li>🧭 Choose the right <strong>similarity metric</strong>: use cosine for NLP</li><li>🔢 Enable <strong>quantization</strong> to reduce memory (use int8 or int1)</li><li>⚙️ Apply <strong>pre-filtering</strong> for fast, scoped search</li><li>🔍 Tune numCandidates carefully for balance</li><li>🧊 Store embeddings in <strong>binData format</strong> for performance</li><li>🧠 Keep embedding <strong>dimensions reasonable</strong> (384–768)</li></ul><h3>🎬 Final Thoughts</h3><p>MongoDB Atlas’s native vector search brings scalable, semantic search to your favorite NoSQL platform. But to truly get the most out of it, apply these best practices:</p><ul><li>Choose the right similarity logic</li><li>Compress and tune wisely</li><li>Filter smartly</li><li>And remember: fast vector search isn’t just about speed — it’s about <em>relevance</em>.</li></ul><p>Whether you’re building AI-powered movie search, product discovery, or knowledge assistants — you’re now equipped to make it intelligent, efficient, and production-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8186c6df852" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Keywords to Vibes: How Vector Search is Revolutionizing Movie Recommendations]]></title>
            <link>https://medium.com/@lklsquare/from-keywords-to-vibes-how-vector-search-is-revolutionizing-movie-recommendations-58875c0be2a7?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/58875c0be2a7</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 02:16:08 GMT</pubDate>
            <atom:updated>2025-07-01T02:16:08.004Z</atom:updated>
            <content:encoded><![CDATA[<h3>✨ Introduction</h3><p>Have you ever tried searching for a movie you can’t quite remember the name of — but you <em>do</em> remember how it made you feel?</p><p>Maybe you’re thinking, “I want something like <em>Interstellar</em>, but with a bit more humor… and a happy ending.”</p><p>You type that into your streaming app, and the results? A total miss. It’s like the system hears your words but not your <em>meaning</em>.</p><p>That’s because most search engines are still stuck in a <strong>keyword world</strong>, where relevance depends on exact word matches — not your intent.</p><p>But a new kind of search is changing everything. One that doesn’t just look at <em>what</em> you type, but understands <em>why</em> you typed it.</p><p>It’s called <strong>vector search</strong>, and it’s the secret sauce behind smarter recommendations, better AI assistants, and modern semantic engines.</p><p>In this article, we’ll explore:</p><ul><li>Why traditional search struggles</li><li>What vector search is (with intuitive analogies and simple math)</li><li>How it transforms a movie database into something that feels <em>intelligent</em></li></ul><p>Whether you’re a movie buff, a tech enthusiast, or an AI professional, this guide will show you how vector search is changing how we find… everything.</p><h3>🎬 The Search That Doesn’t Understand You</h3><p>You just finished watching <em>Interstellar</em> and you’re still thinking about it.</p><p>You’re in the mood for something equally mind-bending — but with a little more optimism and maybe a touch of humor. So, you open your favorite streaming app and type:</p><blockquote>“Something like Interstellar but lighter and funnier.”</blockquote><p>What do you get?</p><blockquote>A space documentary…<br> <em>Apollo 13</em>…<br> Maybe <em>Gravity</em> if you’re lucky.</blockquote><p>Close, but not quite what you meant.</p><p><strong>Why</strong>?</p><p>Because traditional search doesn’t understand what you’re <em>looking for</em> — <strong>it only understands what you <em>typed</em></strong>.</p><p>And that’s the problem.</p><h3>🚪 The Keyword Search Trap</h3><p>Traditional search engines rely on <strong>exact keyword matching</strong>. It’s like asking your friend,</p><blockquote><em>“Hey, got any lighthearted sci-fi?”<br> and they reply,<br> “Well… here are all the movies with the word ‘sci-fi’ in them.”</em></blockquote><p>It’s <strong>fast</strong>. It’s <strong>simple</strong>.<br> But it’s <strong><em>dumb</em></strong>.</p><p>If you don’t use the exact words a movie has been tagged with, you’re out of luck.</p><h3>🧠 What If Search Understood You?</h3><p>Imagine a smarter movie search. One that knew that:</p><ul><li><em>The Martian</em> is uplifting and witty.</li><li><em>WALL-E</em> is emotional and hopeful.</li><li><em>Arrival</em> is intellectual and emotional.</li><li><em>Interstellar</em> is cerebral, epic, and heavy.</li></ul><p>Now, imagine typing:</p><blockquote><em>“Sci-fi about hope, resilience, and human spirit.”</em></blockquote><p>And getting results that <em>feel right</em> — even if the exact words don’t match.</p><p>That’s not science fiction.<br> That’s <strong>vector search</strong>.</p><h3>📦 What Is Vector Search?</h3><p><strong>Vector search</strong> is a new kind of search that understands <em>meaning</em>, not just <em>words</em>.</p><p>It works by transforming your query and your data (like movie descriptions) into <strong>vectors</strong> — mathematical representations of their meaning.</p><p>Then it compares those vectors to find the <strong>closest matches</strong> in meaning.</p><p>Let’s break it down.</p><h3>🧊 For Movie Fans: Imagine Your Movies on a Map</h3><p>Picture a huge wall of DVDs arranged not by title or genre — but by <em>vibe</em>.</p><ul><li>One corner has all the feel-good space movies.</li><li>Another is full of dystopian brain-twisters.</li><li>Somewhere else, the heartwarming animated tales.</li></ul><p>You just watched <em>Inception</em>. You’re in that headspace. You walk to that part of the wall and look around.</p><p>That’s what vector search does.<br> It builds a <strong>map of meaning</strong>, and places every movie on it.</p><p>So when you search for something “like Inception but happier,” it takes you to <em>The Truman Show</em>, <em>Everything Everywhere All at Once</em>, or <em>The Matrix</em> — depending on what it thinks you meant.</p><p>It’s not matching words.<br> It’s matching <em>intent</em>.</p><h3>🔬 For the Curious Technologist: How It Works Under the Hood</h3><p>At a technical level, here’s what happens:</p><ol><li><strong>Embedding the Content</strong><br> Each movie description (e.g., synopsis, reviews, tags) is fed into a machine learning model — like <strong>BERT </strong>or <strong>SentenceTransformers</strong>.<br> The output? A <strong>dense vector</strong> — a list of hundreds of numbers that represent the <em>meaning</em> of the text.<br>Example:</li></ol><blockquote><em>“An astronaut stranded on Mars must use science to survive.”</em><br> becomes:</blockquote><pre>[0.21, -0.14, 0.78, ..., -0.07]</pre><p><strong>2. Embedding the Query</strong><br> When a user types something like:</p><blockquote>“funny survival sci-fi with optimism”<br> That text also gets converted into a similar vector.</blockquote><p><strong>3. Measuring Similarity</strong><br> The system compares your query vector to all the movie vectors using <strong>cosine similarity</strong> — a measure of how aligned two vectors are in multi-dimensional space.</p><p>Think of it as measuring the angle between arrows. Smaller angle = closer in meaning.</p><blockquote>cos⁡(θ)=A⋅B / ∥A∥∥B∥​</blockquote><p><strong>4. Finding Nearest Neighbors</strong><br> Behind the scenes, vector search uses smart algorithms like <strong>HNSW</strong> or <strong>FAISS</strong> to quickly find the closest matches — even in huge databases.</p><h3>🧑‍💻 For AI Professionals: Why It’s a Game Changer</h3><p>You know the limitations of TF-IDF, BM25, and other lexical search engines.</p><p><strong>Vector search</strong> adds:</p><ul><li>Semantic recall: “love triangle in space” pulls up <em>Passengers</em>, not just <em>Love Actually</em> in zero gravity.</li><li>Cold start-friendly recommendations using just one liked title.</li><li>Support for multimodal embeddings: text, images, audio.</li></ul><p>It’s the foundation of modern <strong>semantic search</strong>, <strong>retrieval-augmented generation (RAG)</strong>, and <strong>LLM-powered assistants</strong>.</p><blockquote><em>Want to recommend movies based on user descriptions like “bittersweet but satisfying endings”?<br> Vector search nails it.</em></blockquote><h3>🛠️ Want to Try It?</h3><p>Here’s how you can build your own vector-powered movie search:</p><ul><li>Use sentence-transformers to create embeddings of movie metadata.</li><li>Store vectors in a DB like <strong>Pinecone</strong>, <strong>Weaviate</strong>, or <strong>Milvus, MongoDB</strong>.</li><li>Use <strong>FAISS</strong> for fast search if you’re going local.</li><li>Add filters (like genre or release year) for hybrid precision.</li></ul><p>You’ll have a semantic search system that feels <em>magical</em> compared to traditional methods.</p><h3>🎯 Final Thoughts</h3><p>Search is no longer about matching the right words — it’s about understanding the right <em>meaning</em>.</p><p>Vector search takes us there. It turns our scattered descriptions, vague emotions, and natural language questions into something machines can <em>understand</em>. Not just as text, but as context.</p><p>From recommending the perfect movie to powering AI assistants that “get” you, vector search is quietly reshaping the way we interact with information.</p><p>So the next time your app knows exactly what kind of film you’re in the mood for — even if you didn’t say it directly — remember :<br> <strong>It’s not magic.</strong><br><strong>It’s vectors.</strong></p><p>And this is just the beginning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58875c0be2a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize Your Development: A Recipe for Efficiency]]></title>
            <link>https://medium.com/@lklsquare/dockerize-your-development-a-recipe-for-efficiency-bff8810d0fb8?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/bff8810d0fb8</guid>
            <category><![CDATA[efficient-coding]]></category>
            <category><![CDATA[devlopment]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[good-practices]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 09:53:56 GMT</pubDate>
            <atom:updated>2024-10-26T09:53:56.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AsyEsWAF2z9ngaP2" /><figcaption>Photo by <a href="https://unsplash.com/@carrier_lost?utm_source=medium&amp;utm_medium=referral">Ian Taylor</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Tired of the perennial “It works on my machine” saga? Ready to ditch the dependency hell and embrace a harmonious development workflow? Enter Docker, the culinary secret ingredient that can transform your development process from a chaotic kitchen into a streamlined assembly line.</p><p>Docker has evolved into a critical tool for development teams worldwide, not just for deploying apps but for streamlining development workflows, simplifying dependency management, and making collaboration a breeze. This article will guide you through why Docker is valuable in the development stage, how it works for different backgrounds.</p><h4>Why Do Developers Love Docker?</h4><p>Software development often suffers from “dependency hell” and “it works on my machine” issues. When different team members have varying setups or libraries, inconsistencies arise, leading to bugs and wasted time. Docker solves these challenges by isolating applications in lightweight containers, allowing code to run the same way regardless of where it’s deployed.</p><p>Here’s how Docker can make development smoother, faster, and more efficient, tailored to different levels of technical familiarity.</p><h3>Docker Made Simple: The Container Concept for Everyone</h3><h4>1. Think of Docker as a “Recipe Box” for Your Application</h4><p>Imagine a recipe box where each card contains all the ingredients and steps needed to make a specific dish. Docker is similar: each container holds everything an application needs to run (code, dependencies, libraries) in one portable “recipe.” So, when you share this “recipe” with someone else, they can recreate the exact same dish on their end, no matter what other “ingredients” they have in their kitchen.</p><h4>2. Docker as a Portable Workspace</h4><p>Docker provides isolated workspaces, or “containers,” for each application and its dependencies. These containers are highly portable and don’t need their own operating system, unlike virtual machines. By sharing the underlying OS kernel, Docker runs efficiently, offering a way to package applications with all necessary components. This consistency reduces the time developers spend troubleshooting environment-related issues and helps them focus on building the application.</p><h4>3. Docker’s Microservice Superpowers</h4><p>Under the hood, Docker uses OS-level virtualization, which allows applications to run in isolated user spaces. Each container operates in its own environment, sharing the host OS kernel and using a layered filesystem. Docker’s efficiency allows developers to package and isolate different components of an application, especially in a microservices architecture. A Dockerfile provides the instructions to create a container, and Docker images let teams share consistent environments quickly, powering everything from local testing to CI/CD pipelines.</p><h3>Why Docker is Essential in the Development Stage</h3><p>Using Docker during development offers various benefits beyond deployment:</p><ol><li><strong>Unified Environments Across Teams</strong>: Docker helps every developer work in identical environments, reducing bugs that stem from environmental inconsistencies.</li><li><strong>Efficient Dependency Management</strong>: Docker isolates dependencies, so they don’t conflict with other software or OS versions, helping you avoid compatibility issues.</li><li><strong>Faster Development Cycles</strong>: Docker containers spin up quickly, meaning you can get your environment ready in seconds rather than hours.</li><li><strong>Supports Microservices Architecture</strong>: Each part of an application can be containerized individually, allowing developers to focus on one service without affecting the rest of the application.</li><li><strong>Enhanced Collaboration and Sharing</strong>: Docker images can be shared, enabling team members to access the same development environment and speed up onboarding for new developers.</li><li><strong>Testing in Production-Like Environments</strong>: Docker lets developers test locally in an environment that mirrors production, making it easier to catch bugs early and avoid surprises during deployment.</li></ol><h3>Looking to Dive Deeper? Check Out Our Hands-On Tutorial!</h3><p>If you’re ready to start implementing Docker in your own development environment, our step-by-step tutorial will walk you through setting up a sample Node.js application from scratch, including Docker and Docker Compose configurations for both development and deployment.</p><p>Go to the Full Tutorial <a href="https://github.com/lakshyakumar/docker-for-deployment/tree/main">Here</a>.</p><h3>Contribute Your Own Docker Development Environments!</h3><p>We’d love to see how you’re using Docker in your own development setups! If you have configurations for different development environments — whether it’s for Python, Ruby, Go, or any other stack — please consider contributing to this repository. Your contributions can help other developers learn and create optimized setups for their projects.</p><p>To contribute:</p><ol><li>Fork <a href="https://github.com/lakshyakumar/docker-for-deployment/tree/main">this</a> repository.</li><li>Create a new docker file in docker-files folder (e.g., docker-dev-flask, docker-dev-next, etc.).</li><li>Open a pull request!</li></ol><p>Together, we can build a library of Docker configurations for various development needs. Thank you for helping us grow this resource!</p><h3>Conclusion</h3><p>Docker is a powerful addition to the development toolkit. It simplifies environment setup, dependency management, and collaboration across teams, making development faster and more reliable. By using Docker from the start, developers can avoid many pitfalls that often only emerge during deployment, streamlining the entire process from development to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff8810d0fb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taming the Ethereum Jungle: Wallact Makes Smart Contracts Your Plaything]]></title>
            <link>https://medium.com/@lklsquare/taming-the-ethereum-jungle-wallact-makes-smart-contracts-your-plaything-439d87510d4e?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/439d87510d4e</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 14:09:02 GMT</pubDate>
            <atom:updated>2024-06-14T15:37:23.111Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cDYC0bmeDNVrlEjK" /><figcaption>Photo by <a href="https://unsplash.com/@pinjasaur?utm_source=medium&amp;utm_medium=referral">Paul Esch-Laurent</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The world of blockchain development can be a wild ride, especially when you’re wrangling smart contracts. Fear not, intrepid coders! Wallact, a swanky TypeScript library, swoops in to tame the beast, offering a smooth interface for interacting with Ethereum smart contracts.</p><p>Wallact cuts through the complexity, letting you focus on the real magic: building awesome applications. Buckle up, because we’re about to explore how Wallact simplifies your life (and your code) when it comes to interacting with smart contracts.</p><h3>Wallact: Your Smart Contract Whisperer</h3><p>Wallact boasts a bag of tricks that’ll make you the envy of the developer jungle:</p><ul><li><strong>Say Goodbye to Code Gobbledygook:</strong> Ditch the low-level complexities! Wallact offers easy-to-use methods for both reading and writing data to smart contracts. No more deciphering cryptic web3 calls — Wallact translates them into plain English (well, almost).</li><li><strong>Juggling Contracts Like a Pro:</strong> Need to chat with multiple contracts or manage different entities within your app? Wallact’s got your back. It lets you manage various contract instances through a single interface, keeping your code organized and streamlined.</li><li><strong>Error Handling Like a Boss:</strong> Unexpected errors can turn your development day into a nightmare. Wallact implements try-catch blocks, making error handling a breeze. Now you can build robust applications that can handle anything the blockchain throws their way.</li></ul><h3>Unleashing the Power (Without the Pain)</h3><p>Ready to dive into Wallact and start taming those smart contracts? Here’s what you need to get started:</p><ul><li><strong>Node.js (version 14 or higher recommended):</strong> Because, duh, it’s the foundation of your Node.js and TypeScript kingdom.</li><li><strong>npm (version 6 or higher recommended):</strong> Your trusty package manager to bring Wallact into the fold.</li><li><strong>An Ethereum Wallet Funded with Some ETH:</strong> Gotta have some gas in the tank for those transactions!</li><li><strong>Access to an Ethereum Node (via Infura, Alchemy, or similar services):</strong> Think of it as the internet connection to the blockchain world.</li></ul><p>Once you’ve assembled your developer arsenal, getting Wallact onboard is as easy as:</p><pre>npm i wallact</pre><h3>Time to Play with Your Smart Contracts</h3><p>Now that Wallact is by your side, let’s see how to use it to interact with your smart contracts.</p><p><strong>Peeking Inside Your Smart Contract (Reading Data):</strong></p><p>Want to retrieve some juicy data from a smart contract function? Wallact’s readContract method is your secret weapon. Just tell it the name of the contract method you want to call and any arguments it needs, and Wallact will go fetch the data for you.</p><p>Here’s an example to show you how it’s done:</p><p>TypeScript</p><pre>import { Wallact } from &quot;wallact&quot;;<br><br>async function readData() {<br>  const contractInterface = new Wallact(<br>    &quot;https://rpc-url/&quot;,<br>    &quot;0xContractAddress&quot;,<br>    contractAbi<br>  );<br>  try {<br>    const data = await contractInterface.readContract(&quot;methodName&quot;, [<br>      &quot;arg1&quot;,<br>      &quot;arg2&quot;,<br>    ]);<br>    console.log(&quot;Contract data:&quot;, data);<br>  } catch (error) {<br>    console.error(&quot;Error reading from contract:&quot;, error);<br>  }<br>}</pre><p><strong>Telling Your Smart Contract What to Do (Writing Data):</strong></p><p>Need to interact with your smart contract by writing data? Wallact’s writeContract method is your go-to tool. Just tell it the name of the contract method you want to call, any arguments it needs, and (optionally) the entity (contract instance) to use.</p><p>Here’s how you can write data to your smart contract:</p><p>TypeScript</p><pre>import { Wallact } from &quot;wallact&quot;;<br><br>async function writeData() {<br>  const contractInterface = new Wallact(<br>    &quot;https://rpc-url/&quot;,<br>    &quot;0xContractAddress&quot;,<br>    contractAbi,<br>    &quot;0xYourPrivateKey&quot;<br>  );<br>  try {<br>    const receipt = await contractInterface.writeContract(&quot;methodName&quot;, [<br>      &quot;arg1&quot;,<br>      &quot;arg2&quot;,<br>    ]);<br>    console.log(&quot;Transaction receipt:&quot;, receipt);<br>  } catch (error) {<br>    console.error(&quot;Error writing to contract:&quot;, error);<br>  }<br>}</pre><p><strong>Bonus Level: Handling Multiple Entities</strong></p><p>Have multiple user accounts or entities interacting with your smart contract? Wallact’s got you covered with its addEntityWallet method. Just add additional entities with</p><pre>import { Wallact } from &quot;wallact&quot;;<br><br>async function writeData() {<br>  const contractInterface = new Wallact(<br>    &quot;https://rpc-url/&quot;,<br>    &quot;0xContractddress&quot;,<br>    contractAbi,<br>    &quot;0xYourPrivateKey&quot;,<br>    &quot;ownerEntity&quot;<br>  );<br><br>  contractInterface.addEntityWallet(&quot;verifier&quot;, &quot;0xVerifierPrivateKey&quot;);<br><br>  try {<br>    const receipt = await contractInterface.writeContract(<br>      &quot;methodName&quot;,<br>      [&quot;arg1&quot;, &quot;arg2&quot;],<br>      &quot;verifier&quot;<br>    );<br>    console.log(&quot;Transaction receipt:&quot;, receipt);<br>  } catch (error) {<br>    console.error(&quot;Error writing to contract:&quot;, error);<br>  }<br>}</pre><p><strong>Built-in Conversion Magic</strong></p><p>Working with Ether (ETH) and Wei (the tiniest denomination of Ether) can get confusing. But fear not, Wallact has your back! It provides conversion utilities to make your life easier:</p><ul><li>convertToWei(etherAmount): This handy method takes an amount in Ether and spits out its equivalent in Wei. Perfect for transactions requiring value.</li><li>convertToEth(weiAmount): Need to display balances in a more user-friendly format? This method takes an amount in Wei and converts it back to Ether.</li></ul><p>Here’s a quick example to show you how these work:</p><pre>import { Wallact } from &quot;wallact&quot;;<br><br>const etherAmount = 1; // Example amount in Ether<br>const weiAmount = Wallact.convertToWei(etherAmount);<br>console.log(`${etherAmount} Ether is equivalent to ${weiAmount} Wei.`);<br><br>const weiAmount = BigInt(&quot;1000000000000000000&quot;); // Example amount in Wei<br>const etherAmount = Wallact.convertToEth(weiAmount.toString());<br>console.log(`${weiAmount} Wei is equivalent to ${etherAmount} Ether.`);</pre><p><strong>Creating a Deterministic Wallet</strong></p><p>Wallact allows you to create deterministic wallets using the createWallet function. This function generates a new wallet address based on a provided seed string. The seed string acts like a master password for your wallet, and any wallet created with the same seed will have the same address. This can be useful for generating predictable wallets for testing purposes.</p><p>Here’s an example of how to create a deterministic wallet with Wallact:</p><pre>import { Wallact } from &quot;wallact&quot;;<br><br>let { privateKey, address } = Wallact.createWallet(&quot;userId&quot;, &quot;optionalRandomness&quot;);<br>console.log(address);</pre><p>This code snippet creates a new wallet using the seed string “userId” and extracts the generated wallet address. The address is then logged to the console.</p><p><strong>Retrieving Wallet Address from Private Key</strong></p><p>This static method retrieves the Ethereum wallet address associated with a given private key. It utilizes the ethers.Wallet object to extract the address from the provided private key.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>const privateKey = &quot;YOUR_PRIVATE_KEY&quot;; // Replace with your actual private key<br>const address = Wallact.getWalletAddress(privateKey);<br>console.log(&quot;Wallet address:&quot;, address);</pre><p>This code snippet retrieves the address corresponding to the provided private key and logs it to the console.</p><p><strong>Validating Ethereum Address</strong></p><p>This static method validates whether a given string represents a valid Ethereum address. It leverages the ethers.isAddress function for verification.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>const address = &quot;0x1234567890AbCdEf1234567890AbCdEf1234567890&quot;;<br>if (Wallact.isValidEthereumAddress(address)) {<br>  console.log(&quot;Valid Ethereum address&quot;);<br>} else {<br>  console.log(&quot;Invalid Ethereum address&quot;);<br>}</pre><p>This code snippet checks if the provided string is a valid Ethereum address and logs an appropriate message based on the result.</p><p><strong>Fetching Wallet Balance</strong></p><p>This asynchronous method fetches the current balance of an Ethereum wallet specified by its address. It interacts with the provider to retrieve the balance and returns the value as a number. In case of errors, it throws a new Error with a descriptive message.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>const address = &quot;0x1234567890AbCdEf1234567890AbCdEf1234567890&quot;;<br>(async () =&gt; {<br>  try {<br>    const balance = await Wallact.fetchWalletBalance(address);<br>    console.log(&quot;Wallet balance:&quot;, balance, &quot;Wei&quot;);<br>  } catch (error) {<br>    console.error(&quot;Error fetching wallet balance:&quot;, error.message);<br>  }<br>})();</pre><p>This code snippet fetches the balance of the provided address and logs it to the console in Wei (the smallest denomination of Ether).</p><p><strong>Fetching Latest Block Number</strong></p><p>This asynchronous method retrieves the latest block number from the Ethereum blockchain. It communicates with the provider to get the block number and returns the value as a number. Similar to fetchWalletBalance, it throws an Error on encountering issues.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>(async () =&gt; {<br>  try {<br>    const blockNumber = await Wallact.fetchLatestBlock();<br>    console.log(&quot;Latest block number:&quot;, blockNumber);<br>  } catch (error) {<br>    console.error(&quot;Error fetching latest block number:&quot;, error.message);<br>  }<br>})();</pre><p>This code snippet retrieves the latest block number on the Ethereum blockchain and logs it to the console.</p><p><strong>Getting Transaction Receipt</strong></p><p>This asynchronous method fetches the transaction receipt for a given transaction hash. It interacts with the provider to retrieve the receipt data and returns it as an object. An Error is thrown if the receipt cannot be fetched.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>const txHash = &quot;0xTRANSACTION_HASH&quot;; // Replace with your actual transaction hash<br>(async () =&gt; {<br>  try {<br>    const receipt = await Wallact.getTransactionReceipt(txHash);<br>    console.log(&quot;Transaction receipt:&quot;, receipt);<br>  } catch (error) {<br>    console.error(&quot;Error fetching transaction receipt:&quot;, error.message);<br>  }<br>})();</pre><p>This code snippet retrieves the receipt for a specific transaction identified by its hash and logs the receipt data to the console.</p><p><strong>Writing Data with Confirmation Waiting</strong></p><p>This asynchronous method allows writing data to a smart contract while waiting for a specified number of confirmations on the blockchain. It takes several parameters:</p><ul><li>methodName: The name of the smart contract function you want to call.</li><li>data: An array containing the arguments to be passed to the smart contract function.</li><li>confirmations (Optional): The desired number of confirmations to wait for before resolving the promise (defaults to 5).</li><li>entity (Optional): The name of the contract instance to use for the write operation. If not provided, it attempts to use the default contract instance.</li></ul><p>The method first determines the appropriate contract instance based on the provided entity or default settings. Then, it executes the specified smart contract function using the supplied data. After submitting the transaction, it waits for the desired number of confirmations before resolving the promise and returning the transaction hash. In case of errors, it throws a new Error with a relevant message.</p><p>Here’s an example of how to use this function:</p><pre>import { Wallact } from &quot;wallact&quot;;<br>const methodName = &quot;transfer&quot;; // Replace with your smart contract function name<br>const data = [&quot;0xRECEIVER_ADDRESS&quot;, 100]; // Replace with recipient address and amount<br>(async () =&gt; {<br>  try {<br>    const txHash = await Wallact.writeContractWithConfirmations(methodName, data, 3); // Wait for 3 confirmations<br>    console.log(&quot;Transaction hash:&quot;, txHash);<br>  } catch (error) {<br>    console.error(&quot;Error writing to smart contract:&quot;, error.message);<br>  }<br>})();</pre><p>This code snippet demonstrates writing data to a smart contract function named “transfer” with the provided arguments. It waits for 3 confirmations before resolving and logs the transaction hash.</p><p>By incorporating these functionalities, Wallact provides a versatile toolkit for developers to effectively manage Ethereum wallet addresses, interact with the blockchain, and interact with smart contracts in a robust manner.</p><h3>Thank you for joining us on this exploration!</h3><p>To delve deeper and contribute to the ongoing development, we encourage you to star our project’s <a href="https://github.com/lakshyakumar/wallact">GitHub repository</a>. There, you can find valuable resources and raise Pull Requests (PRs) to address any issues or propose improvements. Let’s build a better blockchain ecosystem together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439d87510d4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hitchhiker’s Guide to Blockchain: Unraveling the Mystery]]></title>
            <link>https://medium.com/@lklsquare/hitchhikers-guide-to-blockchain-unraveling-the-mystery-5f6b0e9aaa25?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f6b0e9aaa25</guid>
            <category><![CDATA[blockchain-101]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sat, 08 Jun 2024 12:50:15 GMT</pubDate>
            <atom:updated>2024-06-08T12:50:15.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Forget the Babel fish, you won’t need it here! This guide is your decoder ring to the fascinating world of blockchain technology. No more confusing jargon or mind-numbing explanations. Blockchain technology is rapidly transforming our world, and understanding its core concepts is no longer optional. This comprehensive guide will equip you with the knowledge to navigate the exciting world of blockchain with confidence. We’ll break down complex terms into easy-to-grasp explanations, empowering you to participate in informed discussions and unlock the vast potential of this revolutionary technology.</p><p><strong>Block: The Foundation of the Chain</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_LFNXyfKa8zNkx3-" /><figcaption>Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_source=medium&amp;utm_medium=referral">Xavi Cabrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a treasure chest overflowing with colorful Lego bricks. Each brick is a <strong>block</strong>, the fundamental unit of data storage on a blockchain. These blocks hold information about transactions, like who sent money to whom, or who just bought a rare digital artwork (NFTs, coming soon!). But unlike your Lego tower, these blocks are specially linked together to create a secure and tamper-proof record.</p><ul><li><strong>Think of it as:</strong> A secure container holding essential transaction data.</li><li><strong>Tech tidbit:</strong> Blocks store data in an encrypted format using cryptographic hash functions. Each block also contains a header with metadata like timestamps, references to the previous block (hash), and a Merkle root (hash of all transactions within the block). This cryptographic chaining ensures data integrity and makes altering a block nearly impossible.</li></ul><p><strong>Blockchain: The Unbreakable Ledger</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jt89T0HSCAa02nD-" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a giant, communal record book that’s constantly growing. This shared ledger is the essence of <strong>blockchain</strong>. Unlike a traditional database controlled by a single entity (like a bank), blockchain is <strong>decentralized</strong>, meaning it’s spread across a network of computers. This distributed nature eliminates the need for a central authority and promotes transparency and security.</p><ul><li><strong>Think of it as:</strong> A giant, shared spreadsheet accessible to everyone on the network.</li><li><strong>Tech tidbit:</strong> This distributed ledger technology (DLT) eliminates the need for a central authority. Each computer participating in the network is called a <strong>node</strong>. Nodes hold a complete copy of the blockchain and validate new transactions through a consensus mechanism (like Proof of Work or Proof of Stake) to ensure the network remains secure and synchronized.</li></ul><p><strong>The Watchdogs of the Blockchain: Understanding Nodes</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_HNEiBFJHebtjiqN" /><figcaption>Photo by <a href="https://unsplash.com/@guerrillabuzz?utm_source=medium&amp;utm_medium=referral">GuerrillaBuzz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a bustling city with vigilant guards patrolling the streets, ensuring security and order. In the realm of blockchain, these guards are simply called <strong>nodes</strong>. They’re the workhorses of the network, playing a crucial role in maintaining its integrity and functionality.</p><p><strong>Think of it as:</strong> A computer system that participates in the blockchain network.</p><p>Nodes act like watchdogs, constantly verifying transactions and keeping the network honest. They communicate with each other through a peer-to-peer network, ensuring everyone is on the same page and no single entity controls the system. This distributed system is what makes blockchain so secure and resistant to manipulation.</p><p><strong>Tech tidbit:</strong> Nodes rely on cryptography to secure the network. They use complex mathematical puzzles to validate transactions and add them to the blockchain. This process, called consensus mechanism, ensures that only legitimate transactions are recorded.</p><p>By working together, these digital watchdogs safeguard the blockchain, keeping it secure and reliable.</p><p><strong>Blockchain Network: A Hive of Activity</strong></p><p>Imagine a bustling beehive, buzzing with activity. In the blockchain network, every bee represents a <strong>node</strong>, a computer that plays a vital role in keeping the system running smoothly. Nodes communicate with each other through a peer-to-peer network, verifying transactions and broadcasting new blocks once validated. Different types of nodes exist, such as full nodes (hold the entire blockchain), lightweight nodes (hold essential data), and validator nodes (participate in the consensus mechanism).</p><ul><li><strong>Think of it as:</strong> A network of computers working together to secure and maintain the blockchain.</li><li><strong>Tech tidbit:</strong> Nodes communicate with each other through a peer-to-peer network. They verify transactions based on the consensus mechanism and broadcast new blocks to the network once validated. Different types of nodes exist, such as full nodes (hold entire blockchain), lightweight nodes (hold essential data), and validator nodes (participate in consensus mechanism).</li></ul><p><strong>Smart Contracts: Self-Executing Agreements</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FFRumASP5A8kXFaj" /><figcaption>Photo by <a href="https://unsplash.com/@victoriano?utm_source=medium&amp;utm_medium=referral">Victoriano Izquierdo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a vending machine that automatically dispenses your favorite drink when you insert the right amount. That’s the magic of <strong>smart contracts</strong>! These are self-executing programs stored on the blockchain that automate agreements between parties without a middleman. The code within the smart contract defines the terms of the agreement, and once specific conditions are met, the contract executes automatically, eliminating the risk of fraud or human error.</p><ul><li><strong>Think of it as:</strong> A self-executing agreement that removes the need for trust between parties.</li><li><strong>Tech tidbit:</strong> Smart contracts are written in programming languages specific to the blockchain platform (e.g., Solidity for Ethereum). They are deployed on the blockchain and reside at a specific address. When pre-defined conditions within the code are met (e.g., payment received), the smart contract executes automatically, ensuring trustless execution of agreements.</li></ul><p><strong>Your Blockchain Wallet: Your Digital Vault</strong></p><p>Imagine a secure app on your phone where you store your digital money (cryptocurrency). That’s your <strong>blockchain wallet</strong>. It’s like a high-tech piggy bank with special features! Unlike a traditional bank account, your blockchain wallet grants you complete control over your funds.</p><ul><li><strong>Think of it as:</strong> A secure app for storing, sending, and receiving cryptocurrencies.</li><li><strong>Tech tidbit:</strong> Your wallet uses cryptographic keys to ensure the security of your funds. It stores your private key, which is like a secret PIN used for signing transactions and proving ownership. It also has a public key, similar to your bank account number, that others can use to send you cryptocurrency.</li></ul><p><strong>What’s an Address? Your Crypto Mailbox</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmYMAkSjZq13JyfV" /><figcaption>Photo by <a href="https://unsplash.com/@rinckad?utm_source=medium&amp;utm_medium=referral">Rinck Content Studio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a unique email address you use to receive messages. On the blockchain, your <strong>address</strong> plays a similar role. It’s a unique code derived from your public key that people can use to send you cryptocurrency. Anyone can see your address on the blockchain, but it doesn’t reveal your private key, keeping your funds secure.</p><ul><li><strong>Think of it as:</strong> Your unique identifier for receiving crypto on the blockchain network.</li><li><strong>Tech tidbit:</strong> Your address is derived from your public key using cryptographic hash functions. It allows others to send you digital assets without revealing your private key.</li></ul><p><strong>Your Bank on Blockchain: Understanding Private and Public Keys</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vwoer1tnvWvrgZ0w" /><figcaption>Photo by <a href="https://unsplash.com/@moneyphotos?utm_source=medium&amp;utm_medium=referral">rc.xyz NFT gallery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine your cryptocurrency holdings are like a secure bank account on a special kind of bank — a blockchain. Unlike traditional banks, there’s no central authority; instead, everyone on the network keeps a copy of all transactions. To ensure security in this decentralized system, you have a special two-key system, similar to your bank account:</p><ul><li><strong>Public Key (Account Number):</strong> Think of this as your bank account number. It’s publicly available information, like the number printed on your checks. Anyone can use this number to send you cryptocurrency, just like they can deposit money into your account using your account number.</li><li><strong>Private Key (ATM PIN):</strong> This is your top-secret key, just like your ATM PIN. It should never be shared with anyone. This private key acts like your digital signature, proving you’re the authorized owner when you want to withdraw funds (cryptocurrency) from your account.</li></ul><p><strong>Think of it as:</strong> An account number for deposits (public key) where anyone can send you funds. But to withdraw money from your secure vault pin (private key), you need the secret key itself.</p><p><strong>Coins vs. Tokens: Digital Money Explained</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YVcxYFqP_zXdk1Ki" /><figcaption>Photo by <a href="https://unsplash.com/@eprouzet?utm_source=medium&amp;utm_medium=referral">Eric Prouzet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine gold coins and arcade tokens. <strong>Coins</strong> on the blockchain are like gold coins — they are native to a specific blockchain and function primarily as a medium of exchange (e.g., Bitcoin on the Bitcoin blockchain). <strong>Tokens</strong>, on the other hand, are more like arcade tokens. They can represent various things, like digital assets (security tokens), access to a service (utility tokens), or even ownership of a digital artwork (NFTs).</p><ul><li><strong>Think of it as:</strong> Coins are the native currency of a blockchain, while tokens represent a wider range of digital assets or functionalities.</li><li><strong>Tech tidbit:</strong> Coins have their own blockchain, while tokens can be built on top of any existing blockchains like Ethereum.</li></ul><p><strong>Transaction Hash: Your Digital Receipt</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*skZ1Rs4gyimBTTB7" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Whenever you buy something online, you get a receipt. A <strong>transaction hash</strong> on the blockchain is like a digital receipt. It’s a unique code generated for every transaction on the blockchain, providing a permanent and immutable record of the transaction details.</p><ul><li><strong>Think of it as:</strong> A unique fingerprint for every transaction on the blockchain.</li><li><strong>Tech tidbit:</strong> The transaction hash is generated using cryptographic functions and is publicly viewable on the blockchain explorer. It helps track and verify transactions, ensuring their legitimacy.</li></ul><p><strong>Gas Fees: Fueling the Blockchain</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XDfSXipylWKKih2q" /><figcaption>Photo by <a href="https://unsplash.com/@derstudi?utm_source=medium&amp;utm_medium=referral">Timon Studler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine using a busy highway to deliver your groceries. You might have to pay a small fee to use the express lane. <strong>Gas fees</strong> on the blockchain are similar. They are small amounts of cryptocurrency paid to miners (or validators) who process and verify transactions on the network. These fees incentivize miners to participate and maintain the security of the blockchain.</p><ul><li><strong>Think of it as:</strong> A small fee paid to miners for processing and validating your transaction on the network including a fee for the infra and computation.</li><li><strong>Tech tidbit:</strong> Gas fees is actual cost we pay for the infra and the computation we utilize on a blockchain network. Gas fees vary depending on network congestion and the complexity of the transaction. Users can often choose a gas fee amount to influence the speed of their transaction processing.</li></ul><p><strong>Stablecoins: Taming the Crypto Rollercoaster</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aABxrGZAQoMUiPuD" /><figcaption>Photo by <a href="https://unsplash.com/@coinwire?utm_source=medium&amp;utm_medium=referral">CoinWire Japan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine a special type of coin that doesn’t change its value as much as other cryptocurrencies. <strong>Stablecoins</strong> are like that — they’re cryptocurrencies pegged to real-world assets like the US dollar or gold. This peg helps to stabilize their value, making them a less volatile alternative to traditional cryptocurrencies.</p><ul><li><strong>Think of it as:</strong> Cryptocurrencies with a stable value, often pegged to real-world assets.</li><li><strong>Tech tidbit:</strong> Stablecoins can be backed by fiat currency reserves, crypto assets, or a combination of both. This backing mechanism helps maintain their price stability.</li></ul><p><strong>What is an NFT? A Unique Digital Collectible</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*752r4HSeOuEwD81m" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine owning a one-of-a-kind trading card that no one else can replicate. <strong>Non-fungible tokens (NFTs)</strong> are like that — they represent unique digital assets on a blockchain. Unlike fungible tokens (like cryptocurrencies), each NFT has a unique identifier and ownership record, making them ideal for representing digital collectibles like artwork, music, or even in-game items.</p><ul><li><strong>Think of it as:</strong> A digital certificate of ownership for unique digital assets.</li><li><strong>Tech tidbit:</strong> NFTs are created using smart contracts and reside on a blockchain. They can be bought, sold, or traded on dedicated NFT marketplaces.</li></ul><p><strong>Centralized vs. Decentralized Exchanges: Where to Trade Crypto</strong></p><p>Imagine a traditional stock exchange where you buy and sell assets through a central authority. <strong>Centralized exchanges (CEXs)</strong> are similar — they act as intermediaries for cryptocurrency trading, holding user funds and facilitating transactions. On the other hand, <strong>decentralized exchanges (DEXs)</strong> are like peer-to-peer marketplaces where users trade directly with each other without a central authority.</p><ul><li><strong>Centralized Exchanges (CEXs):</strong> User-friendly, offer fiat on-ramps (buying crypto with traditional currency), but may have limitations on tradable assets and higher fees.</li><li><strong>Decentralized Exchanges (DEXs):</strong> Offer greater control and security for users, but can be more complex to use and have lower trading volume compared to CEXs.</li></ul><p><strong>Transaction Time: How Long Does it Take to transact on blockchain?</strong></p><p>Imagine waiting in line at the bank — transaction speeds can vary depending on the blockchain network. Transaction times on a blockchain depend on factors like network congestion and the specific blockchain protocol. Some blockchains prioritize faster transaction speeds, while others prioritize security and decentralization, leading to slower transaction times.</p><ul><li><strong>Think of it as:</strong> The time it takes for a transaction to be confirmed and added to the blockchain.</li><li><strong>Tech tidbit:</strong> Transaction times can range from a few seconds to several minutes depending on the network. Users can often pay higher gas fees to expedite their transactions.</li></ul><p><strong>Block Explorers: Unveiling the Blockchain</strong></p><p>Imagine a public record office where you can view historical documents. <strong>Block explorers</strong> are similar — they are online tools that allow anyone to view and search the blockchain for information about transactions, addresses, and blocks. This transparency is a key feature of blockchain technology.</p><ul><li><strong>Think of it as:</strong> Public search engines for blockchain data.</li><li><strong>Tech tidbit:</strong> Block explorers allow users to track the status of transactions, verify balances, and explore historical blockchain data.</li></ul><p><strong>Consensus Mechanism: The Pillars of Trust</strong></p><p>Imagine a group of people agreeing on the truth — that’s the essence of a <strong>consensus mechanism</strong> in blockchain. It’s the process by which nodes on the network agree on the validity of transactions and the current state of the blockchain. Different blockchains use different consensus mechanisms, such as Proof of Work (PoW) or Proof of Stake (PoS), to ensure a secure and decentralized network.</p><ul><li><strong>Think of it as:</strong> The process by which blockchain networks reach agreement on the validity of transactions.</li><li><strong>Tech tidbit:</strong> The chosen consensus mechanism impacts factors like transaction speed, energy consumption, and network security.</li></ul><p><strong>On-Chain vs. Off-Chain Data: Where Does Information Live?</strong></p><p>Imagine storing important documents in a secure vault (on-chain) and less critical data in a filing cabinet (off-chain). Blockchain networks also differentiate between <strong>on-chain data</strong> and <strong>off-chain data</strong>. On-chain data refers to information directly stored on the blockchain, while off-chain data resides on external databases or storage solutions.</p><ul><li><strong>On-Chain Data:</strong> Secure, transparent, but limited storage capacity.</li><li><strong>Off-Chain Data:</strong> More scalable, but less transparent and potentially less secure.</li><li><strong>Tech tidbit:</strong> Blockchain networks often leverage off-chain storage for scalability purposes, while still maintaining the core security benefits of on-chain data for critical information.</li></ul><p><strong>Blockchain’s Blazing Speed: Advancements in Recent Years</strong></p><p>The past few years haven’t just been about theoretical advancements; they’ve seen real-world solutions emerge to address some of blockchain’s limitations. Here’s a look at some key breakthroughs:</p><ul><li><strong>Zero-Knowledge Proofs (ZKPs):</strong> Imagine proving you’re old enough to enter a club without revealing your actual birthdate. ZKPs offer a similar level of privacy for transactions on the blockchain, allowing for verification without exposing sensitive data.</li><li><strong>Layer-2 Solutions:</strong> Think of adding extra lanes to a highway to ease congestion. Layer-2 protocols operate on top of existing blockchains, scaling transaction processing and reducing fees.</li><li><strong>Account Abstraction:</strong> Imagine a universal login for all your online accounts. Account abstraction simplifies user experience by separating complex cryptographic keys from everyday interactions with blockchain applications.</li></ul><p>These advancements are paving the way for a future where blockchain is not just secure and transparent, but also fast, user-friendly, and ready for mass adoption.</p><p><strong>A Multifaceted Ecosystem: A Look at Different Blockchain Types</strong></p><p>The blockchain landscape is teeming with innovation, with various platforms catering to specific needs. Here’s a glimpse into some popular blockchain types:</p><ul><li><strong>EVM-Compatible Blockchains (e.g., Avalanche, Polygon):</strong> These blockchains are like cousins to Ethereum, sharing the Ethereum Virtual Machine (EVM) and allowing developers to easily port existing Ethereum applications.</li><li><strong>Hyperledger Fabric:</strong> Imagine a permissioned blockchain designed for businesses. Hyperledger Fabric offers a modular architecture ideal for private and consortium blockchains.</li><li><strong>Solana:</strong> Picture a high-performance blockchain with blazing-fast transaction speeds. Solana utilizes a unique Proof-of-History consensus mechanism to achieve its impressive scalability.</li><li><strong>Bitcoin</strong>: Bitcoin is the most well-known cryptocurrency and blockchain, making it a more universally understood reference point. Bitcoin played a pivotal role in launching the blockchain revolution, highlighting its historical impact on the technology.</li><li><strong>And Many More:</strong> Imagine tracking the origin and journey of a diamond from mine to proving the complex model of AI has a use case for blockchains.</li></ul><p>This diversity reflects the ongoing evolution of blockchain technology. Different blockchains excel in specific areas, and their coexistence fosters a rich ecosystem that caters to a vast array of use cases.</p><p><strong>Conclusion: Embracing a Blockchain-Powered Future</strong></p><p>The future of blockchain is brimming with possibilities. As scalability solutions mature, user experience improves, and interoperability increases, blockchain is poised to revolutionize numerous industries. From streamlining global trade to securing our digital identities, the potential applications are truly limitless.</p><p>By equipping yourself with the knowledge in this guide, you’ve taken a significant step towards becoming an active participant in this exciting technological revolution. Embrace the future, explore the potential of different blockchains, and join the movement towards a more secure, transparent, and connected world powered by blockchain technology!</p><p><strong>Thank you for joining us on this exploration!</strong></p><p>Thank you for joining me on this first date with blockchain! There’s so much more to discover, but you’re now well on your way to navigating conversations and exploring this fascinating technology further. Feel free to keep exploring, and if you have any questions, don’t hesitate to ask!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f6b0e9aaa25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reaching New Heights: Iteration 7 of Our Smart Contract Wallet]]></title>
            <link>https://medium.com/@lklsquare/reaching-new-heights-iteration-7-of-our-smart-contract-wallet-2cdbc70b595b?source=rss-d7d477cfa30------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cdbc70b595b</guid>
            <category><![CDATA[erc-4337]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[gasless-transactions]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[account-abstraction]]></category>
            <dc:creator><![CDATA[lakshya kumar]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 10:04:34 GMT</pubDate>
            <atom:updated>2024-04-28T10:04:34.940Z</atom:updated>
            <content:encoded><![CDATA[<p>The evolution continues! Iteration seven of our Smart Contract Wallet development ushers in a revolutionary concept: <em>gasless transactions</em>. This exciting advancement is made possible by the introduction of the Paymaster contract. Imagine a world where you can execute transactions within the wallet and interact with smart contracts without worrying about gas fees!</p><p>The Paymaster plays a pivotal role in achieving this vision. Alongside this innovation, we’ve also refined the underlying structure of <em>user operations</em> (UserOp) by introducing a new field named paymasterAndData. This addition provides the necessary framework for seamless integration with the Paymaster contract. To ensure seamless interaction, the Entrypoint contract has been adapted to handle paymaster-related parameters effectively.</p><p>Get ready to explore the exciting possibilities of gasless transactions in this chapter of our Smart Contract Wallet journey!</p><h3>Part of a Series</h3><p>This article is part of a comprehensive tutorial series designed to guide you through Account Abstraction or ERC-4337. If you’re new to the series, you can find the starting point <a href="https://medium.com/@lklsquare/demistifying-account-abstraction-a-step-by-step-exploration-of-erc-4337-2cc09c0d3f0c">here</a>. The previous tutorial in this series can be found <a href="https://medium.com/@lklsquare/unveiling-the-future-iteration-6-of-our-smart-contract-wallet-076841e0b67e">here</a>.</p><p>Throughout this series, we’ll cover a variety of topics related to Account Abstraction. We’ll provide clear explanations, practical examples, and troubleshooting tips to help you on your learning journey.</p><p>To ensure you have access to all the code examples used throughout this series, we’ve created a dedicated repository on GitHub. <a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration">This </a>repository will be constantly updated as we progress through the tutorials. By following the repository, you can easily clone it to your local machine and follow along with the code demonstrations.</p><h3>Introducing Paymaster</h3><p>The Paymaster contract facilitates gasless transactions by managing deposits and handling transaction validation. It integrates with the Entrypoint and provides mechanisms to add and withdraw deposits. Notable features include:</p><ul><li>Gasless Transactions: Users can perform transactions without worrying about gas fees, as the Paymaster handles the gas costs.</li><li>Validation and Parsing: Paymaster includes functions such as validatePaymasterUserOp and parsePaymasterAndData to validate and parse paymaster data, ensuring the integrity of transactions.</li></ul><h3>Tests</h3><p>We have updated the testing script to incorporate deployment and validation of the Paymaster contract. Additionally, testing scenarios for transactions involving Paymaster have been added to ensure robust functionality.</p><ol><li>Let’s kick off the deployment process by incorporating the VerifyingPaymasterV7 contract into the deployContract() function</li></ol><pre>...<br>    const Paymaster = await ethers.getContractFactory(&quot;VerifyingPaymasterV7&quot;);<br>    const paymaster = await Paymaster.deploy(<br>      await entryPoint.getAddress(),<br>      owner.address<br>    );<br>    await paymaster.waitForDeployment();<br>    await owner.sendTransaction({<br>      to: await paymaster.getAddress(),<br>      value: ethers.parseEther(&quot;1&quot;),<br>    });<br>    await paymaster.addDeposit({ value: ethers.parseEther(&quot;0.5&quot;) });<br>    ...</pre><p>2. Once the paymaster contract is deployed, it&#39;s crucial to validate its deployment to ensure its functionality. lets write a deplyment test case:</p><pre>describe(&quot;Deployment&quot;, function () {<br>    it(&quot;Should Deploy wallet, token, paymaster and entrypoint&quot;, async function () {<br>      ...<br>      expect(await paymaster.getAddress()).to.exist;<br>    });<br>  });</pre><p>3. To comprehensively test the Paymaster contract, it&#39;s imperative to include various testing scenarios. Below is a test case for scenario that verifies, calls, and executes a user operation with the Paymaster contract:</p><pre>it(&quot;Test should verify, call and execute userop with paymaster 0x&quot;, async function () {<br>  const { token, wallet, paymaster, entryPoint, owner, otherAccount } =<br>    await loadFixture(deployContracts);<br>  const MOCK_VALID_UNTIL = &quot;0x00000000deadbeef&quot;;<br>  const MOCK_VALID_AFTER = &quot;0x0000000000001234&quot;;<br><br>  let nonce = await wallet.getNonce();<br>  let { maxFeePerGas, maxPriorityFeePerGas, verificationGasLimit } =<br>    await getGasFee(ethers.provider);<br>  const { callData, callGasLimit } = await encodeUserOpCallDataAndGasLimit(<br>    wallet,<br>    owner,<br>    {<br>      target: await token.getAddress(),<br>      value: 0,<br>      data: token.interface.encodeFunctionData(&quot;transfer&quot;, [<br>        otherAccount.address,<br>        ethers.parseEther(&quot;10&quot;),<br>      ]),<br>    }<br>  );<br>  let userOp = {<br>    ...getUserOp(<br>      await wallet.getAddress(),<br>      nonce,<br>      callData,<br>      callGasLimit,<br>      verificationGasLimit,<br>      1000000,<br>      maxFeePerGas,<br>      maxPriorityFeePerGas<br>    ),<br>    paymasterAndData: &quot;0x&quot;,<br>  };<br>  const pmHash = await paymaster.getHash(<br>    userOp,<br>    MOCK_VALID_UNTIL,<br>    MOCK_VALID_AFTER<br>  );<br>  const pmSignedMessage = await owner.signMessage(ethers.toBeArray(pmHash));<br>  let hash = await wallet.hashFunction(userOp);<br>  let { chainId } = await ethers.provider.getNetwork();<br><br>  const codedData = abiCoder.encode(<br>    [&quot;bytes32&quot;, &quot;address&quot;, &quot;uint256&quot;],<br>    [hash, await entryPoint.getAddress(), chainId]<br>  );<br>  let encodedData = ethers.keccak256(codedData);<br>  const signedMessage = await owner.signMessage(ethers.toBeArray(encodedData));<br>  const paymasterAndData = ethers.concat([<br>    await paymaster.getAddress(),<br>    abiCoder.encode([&quot;uint48&quot;, &quot;uint48&quot;], [MOCK_VALID_UNTIL, MOCK_VALID_AFTER]),<br>    pmSignedMessage,<br>  ]);<br>  userOp = {<br>    ...userOp,<br>    signature: signedMessage,<br>    paymasterAndData,<br>  };<br>  await expect(<br>    entryPoint<br>      .connect(otherAccount)<br>      .simulateHandleOp(userOp, userOp.sender, userOp.callData)<br>  )<br>    .to.be.revertedWithCustomError(entryPoint, &quot;ExecutionResult&quot;)<br>    .withArgs(anyValue, anyValue, anyValue, anyValue, true, anyValue);<br>  const txn = await entryPoint<br>    .connect(otherAccount)<br>    .handleOps(userOp, otherAccount.address);<br>  txn.wait();<br>  expect(await token.balanceOf(otherAccount.address)).to.equal(<br>    ethers.parseEther(&quot;10&quot;)<br>  );<br>});</pre><p>This test scenario encompasses the verification, invocation, and execution of a user operation using the paymaster contract, thereby ensuring its seamless functionality within the Ethereum ecosystem.</p><h3>Development</h3><h3>EntrypointV7</h3><p>The contracts\07_EntryPointV7.sol contract has undergone significant changes and enhancements to improve its functionality and robustness. Let&#39;s delve into the key modifications and their benefits:</p><ol><li><strong>Struct Refactoring</strong>: The ValidationData struct has been introduced to encapsulate validation-related data, enhancing code readability and organization.</li><li><strong>Event Declaration</strong>: An UserOperationEvent event has been declared to facilitate event-driven architecture, providing visibility into user operation events for monitoring and analysis purposes.</li><li><strong>Function Refinements</strong>:</li></ol><ul><li>The getMemoryBytesFromOffset function has been implemented to retrieve memory bytes from a specified offset, streamlining memory management operations within the contract.</li><li>Refinements have been made to the _validateSenderAndPaymaster function to handle edge cases more gracefully, such as reverting with meaningful error messages when sender or paymaster accounts are not deployed.</li></ul><p>4. Simulation and Validation:</p><ul><li>The _simulateOnlyValidation function has been introduced to simulate validation processes without executing actual operations, enabling efficient testing and validation of user operations.</li><li>A new _intersectTimeRange function has been added to calculate the intersection of time ranges, enhancing validation accuracy and ensuring proper execution within specified time constraints.</li></ul><p>5. Execution and Handling:</p><ul><li>The simulateHandleOp function now incorporates comprehensive validation checks, gas calculations, and execution handling for user operations, promoting efficient and secure contract execution.</li><li>Internal functions such as _handlePostOp and _executeUserOp have been refined to handle post-operation tasks, gas management, and error handling, ensuring consistent and reliable contract behavior.</li></ul><p>6. Prepayment Validation:</p><ul><li>Extensive modifications have been made to the _validatePrepayment function to validate user prepayments, nonce validity, and paymaster interactions, fostering trust and security in transaction processing.</li><li>Improved validation logic ensures accurate verification of account and paymaster data, mitigating potential risks and vulnerabilities in the transaction lifecycle.</li></ul><pre>contract EntryPointV7 is NonceManager, StakeManager, ReentrancyGuard {<br>    ...<br>    struct ValidationData {<br>        uint48 validAfter;<br>        uint48 validUntil;<br>    }<br>    ...<br>    event UserOperationEvent(<br>        bytes32 indexed userOpHash,<br>        address indexed sender,<br>        address indexed paymaster,<br>        uint256 nonce,<br>        bool success,<br>        uint256 actualGasCost,<br>        uint256 actualGasUsed<br>    );<br><br>    function getMemoryBytesFromOffset(<br>        uint256 offset<br>    ) internal pure returns (bytes memory data) {<br>        assembly {<br>            data := offset<br>        }<br>    }<br><br>    function _validateSenderAndPaymaster(<br>        address sender,<br>        bytes calldata paymasterAndData<br>    ) external view {<br>        if (sender.code.length == 0) {<br>            revert(&quot;AA20 account not deployed&quot;);<br>        }<br>        if (paymasterAndData.length &gt;= 20) {<br>            address paymaster = address(bytes20(paymasterAndData[0:20]));<br>            if (paymaster.code.length == 0) {<br>                // it would revert anyway. but give a meaningful message<br>                revert(&quot;AA30 paymaster not deployed&quot;);<br>            }<br>        }<br>        // always revert<br>        revert(&quot;&quot;);<br>    }<br>    function _simulateOnlyValidation(<br>        UserOperation calldata userOp<br>    ) internal view {<br>        try<br>            this._validateSenderAndPaymaster(<br>                userOp.sender,<br>                userOp.paymasterAndData<br>            )<br>        {} catch Error(string memory revertReason) {<br>            if (bytes(revertReason).length != 0) {<br>                revert FailedOp(0, revertReason);<br>            }<br>        }<br>    }<br><br>    function _intersectTimeRange(<br>        uint256 validationData,<br>        uint256 paymasterValidationData<br>    ) public pure returns (uint48 validAfter, uint48 validUntil) {<br>        (uint48 accValidUntil, uint48 accValidAfter) = _parseValidationData(<br>            validationData<br>        );<br>        (uint48 pmValidUntil, uint48 pmValidAfter) = _parseValidationData(<br>            paymasterValidationData<br>        );<br>        if (accValidAfter &lt; pmValidAfter) validAfter = pmValidAfter;<br>        if (accValidUntil &gt; pmValidUntil) validUntil = pmValidUntil;<br>    }<br><br>    function simulateHandleOp(<br>        UserOperation calldata op,<br>        address target,<br>        bytes calldata targetCallData<br>    ) external {<br>        UserOpInfo memory opInfo;<br>        _simulateOnlyValidation(op);<br>        (<br>            uint256 validationData,<br>            uint256 paymasterValidationData<br>        ) = _validatePrepayment(op, opInfo);<br>        (uint48 validAfter, uint48 validUntil) = _intersectTimeRange(<br>            validationData,<br>            paymasterValidationData<br>        );<br><br>        numberMarker();<br>        uint256 paid = _executeUserOp(op, opInfo);<br>        numberMarker();<br>        bool targetSuccess;<br>        bytes memory targetResult;<br>        if (target != address(0)) {<br>            (targetSuccess, targetResult) = target.call(targetCallData);<br>        }<br>        revert ExecutionResult(<br>            opInfo.preOpGas,<br>            paid,<br>            validAfter,<br>            validUntil,<br>            targetSuccess,<br>            targetResult<br>        );<br>    }<br><br>    function _handlePostOp(<br>        IPaymaster.PostOpMode mode,<br>        UserOpInfo memory opInfo,<br>        bytes memory context,<br>        uint256 actualGas<br>    ) private returns (uint256 actualGasCost) {<br>        uint256 preGas = gasleft();<br>        address refundAddress;<br>        MemoryUserOp memory mUserOp = opInfo.mUserOp;<br>        uint256 gasPrice = getUserOpGasPrice(mUserOp);<br>        address paymaster = mUserOp.paymaster;<br>        if (paymaster == address(0)) {<br>            refundAddress = mUserOp.sender;<br>        } else {<br>            refundAddress = paymaster;<br>            if (context.length &gt; 0) {<br>                actualGasCost = actualGas * gasPrice;<br>                if (mode != IPaymaster.PostOpMode.postOpReverted) {<br>                    IPaymaster(paymaster).postOp{<br>                        gas: mUserOp.verificationGasLimit<br>                    }(mode, context, actualGasCost);<br>                } else {<br>                    // solhint-disable-next-line no-empty-blocks<br>                    try<br>                        IPaymaster(paymaster).postOp{<br>                            gas: mUserOp.verificationGasLimit<br>                        }(mode, context, actualGasCost)<br>                    {} catch Error(string memory reason) {<br>                        revert FailedOp(<br>                            0,<br>                            string.concat(&quot;AA50 postOp reverted: &quot;, reason)<br>                        );<br>                    } catch {<br>                        revert FailedOp(0, &quot;AA50 postOp revert&quot;);<br>                    }<br>                }<br>            }<br>        }<br>        actualGas += preGas - gasleft();<br>        actualGasCost = actualGas * gasPrice;<br>        if (opInfo.prefund &lt; actualGasCost) {<br>            revert FailedOp(0, &quot;AA51 prefund below actualGasCost&quot;);<br>        }<br>        uint256 refund = opInfo.prefund - actualGasCost;<br>        _incrementDeposit(refundAddress, refund);<br>        bool success = mode == IPaymaster.PostOpMode.opSucceeded;<br>        emit UserOperationEvent(<br>            opInfo.userOpHash,<br>            mUserOp.sender,<br>            mUserOp.paymaster,<br>            mUserOp.nonce,<br>            true,<br>            actualGasCost,<br>            actualGas<br>        );<br>    }<br><br>    function innerHandleOp(<br>        bytes memory callData,<br>        UserOpInfo memory opInfo,<br>        bytes calldata context<br>    ) external returns (uint256 actualGasCost) {<br>        uint256 preGas = gasleft();<br>        require(msg.sender == address(this), &quot;AA92 internal call only&quot;);<br>        MemoryUserOp memory mUserOp = opInfo.mUserOp;<br>        uint callGasLimit = mUserOp.callGasLimit;<br><br>        unchecked {<br>            // handleOps was called with gas limit too low. abort entire bundle.<br>            if (<br>                gasleft() &lt; callGasLimit + mUserOp.verificationGasLimit + 5000<br>            ) {<br>                assembly {<br>                    mstore(0, INNER_OUT_OF_GAS)<br>                    revert(0, 32)<br>                }<br>            }<br>        }<br>        IPaymaster.PostOpMode mode = IPaymaster.PostOpMode.opSucceeded;<br>        if (callData.length &gt; 0) {<br>            bool success = call(mUserOp.sender, 0, callData, callGasLimit);<br>            if (!success) {<br>                bytes memory result = getReturnData(REVERT_REASON_MAX_LEN);<br>                if (result.length &gt; 0) {<br>                    emit UserOperationRevertReason(<br>                        opInfo.userOpHash,<br>                        mUserOp.sender,<br>                        mUserOp.nonce,<br>                        result<br>                    );<br>                }<br>                mode = IPaymaster.PostOpMode.opReverted;<br>            }<br>        }<br>        unchecked {<br>            uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;<br>            //note: opIndex is ignored (relevant only if mode==postOpReverted, which is only possible outside of innerHandleOp)<br>            return _handlePostOp(mode, opInfo, context, actualGas);<br>        }<br>    }<br><br>    function _executeUserOp(<br>        UserOperation calldata userOp,<br>        UserOpInfo memory opInfo<br>    ) private returns (uint256 collected) {<br>        uint256 preGas = gasleft();<br>        bytes memory context = getMemoryBytesFromOffset(opInfo.contextOffset);<br>        try this.innerHandleOp(userOp.callData, opInfo, context) returns (<br>            uint256 _actualGasCost<br>        ) {<br>            collected = _actualGasCost;<br>        } catch {<br>            bytes32 innerRevertCode;<br>            assembly {<br>                returndatacopy(0, 0, 32)<br>                innerRevertCode := mload(0)<br>            }<br>            // handleOps was called with gas limit too low. abort entire bundle.<br>            if (innerRevertCode == INNER_OUT_OF_GAS) {<br>                //report paymaster, since if it is not deliberately caused by the bundler,<br>                // it must be a revert caused by paymaster.<br>                revert FailedOp(0, &quot;AA95 out of gas&quot;);<br>            }<br><br>            uint256 actualGas = preGas - gasleft() + opInfo.preOpGas;<br>            collected = _handlePostOp(<br>                IPaymaster.PostOpMode.postOpReverted,<br>                opInfo,<br>                context,<br>                actualGas<br>            );<br>        }<br>    }<br><br>    function handleOps(<br>        UserOperation calldata ops,<br>        address payable beneficiary<br>    ) public nonReentrant {<br>        unchecked {<br>            uint256 preGas = gasleft();<br>            UserOpInfo memory opInfo;<br>            (<br>                uint256 validationData,<br>                uint256 paymasterValidationData<br>            ) = _validatePrepayment(ops, opInfo);<br>            _validateAccountAndPaymasterValidationData(<br>                validationData,<br>                paymasterValidationData,<br>                address(0)<br>            );<br>            uint256 collected = _executeUserOp(ops, opInfo);<br>            uint256 actualGas = preGas - gasleft();<br>            (actualGas);<br>            _compensate(beneficiary, collected);<br>        }<br>    }<br><br>    function verifyCalculateGasAndPrefund(<br>        UserOperation calldata ops,<br>        UserOpInfo memory opInfo,<br>        MemoryUserOp memory mUserOp<br>    )<br>        public<br>        returns (<br>            uint256 validationData,<br>            uint256 gasUsedByValidateAccountPrepayment<br>        )<br>    {<br>        uint256 preGas = gasleft();<br>        opInfo.userOpHash = getUserOpHash(ops);<br>        // validate all numeric values in userOp are well below 128 bit, so they can safely be added<br>        // and multiplied without causing overflow<br>        uint256 maxGasValues = mUserOp.preVerificationGas |<br>            mUserOp.verificationGasLimit |<br>            mUserOp.callGasLimit |<br>            ops.maxFeePerGas |<br>            ops.maxPriorityFeePerGas;<br>        require(maxGasValues &lt;= type(uint120).max, &quot;AA94 gas values overflow&quot;);<br><br>        uint256 requiredPreFund = _getRequiredPrefund(mUserOp);<br>        uint256 missingAccountFunds = 0;<br>        uint256 bal = balanceOf(mUserOp.sender);<br>        missingAccountFunds = bal &gt; requiredPreFund ? 0 : requiredPreFund - bal;<br><br>        address sender = mUserOp.sender;<br>        try<br>            Wallet(sender).validateSignatureAndSend{<br>                gas: mUserOp.verificationGasLimit<br>            }(ops, opInfo.userOpHash, requiredPreFund)<br>        returns (uint256 _validationData) {<br>            validationData = _validationData;<br>        } catch Error(string memory revertReason) {<br>            revert FailedOp(0, string.concat(&quot;AA23 reverted: &quot;, revertReason));<br>        } catch {<br>            revert FailedOp(0, &quot;AA23 reverted (or OOG)&quot;);<br>        }<br>        deposits[sender] = deposits[sender] - requiredPreFund;<br>        gasUsedByValidateAccountPrepayment = preGas - gasleft();<br>    }<br><br>    function _validatePaymasterPrepayment(<br>        UserOperation calldata op,<br>        UserOpInfo memory opInfo,<br>        uint256 requiredPreFund,<br>        uint256 gasUsedByValidateAccountPrepayment<br>    ) internal returns (bytes memory context, uint256 validationData) {<br>        unchecked {<br>            MemoryUserOp memory mUserOp = opInfo.mUserOp;<br>            uint256 verificationGasLimit = mUserOp.verificationGasLimit;<br>            require(<br>                verificationGasLimit &gt; gasUsedByValidateAccountPrepayment,<br>                &quot;AA41 too little verificationGas&quot;<br>            );<br>            uint256 gas = verificationGasLimit -<br>                gasUsedByValidateAccountPrepayment;<br><br>            address paymaster = mUserOp.paymaster;<br>            uint256 deposit = deposits[paymaster];<br>            if (deposit &lt; requiredPreFund) {<br>                revert FailedOp(0, &quot;AA31 paymaster deposit too low&quot;);<br>            }<br>            deposits[paymaster] = uint112(deposit - requiredPreFund);<br>            try<br>                IPaymaster(paymaster).validatePaymasterUserOp{gas: gas}(<br>                    op,<br>                    opInfo.userOpHash,<br>                    requiredPreFund<br>                )<br>            returns (bytes memory _context, uint256 _validationData) {<br>                context = _context;<br>                validationData = _validationData;<br>            } catch Error(string memory revertReason) {<br>                revert FailedOp(<br>                    0,<br>                    string.concat(&quot;AA33 reverted: &quot;, revertReason)<br>                );<br>            } catch {<br>                revert FailedOp(0, &quot;AA33 reverted (or OOG)&quot;);<br>            }<br>        }<br>    }<br><br>    function _validateAccountAndPaymasterValidationData(<br>        uint256 validationData,<br>        uint256 paymasterValidationData,<br>        address expectedAggregator<br>    ) internal view {<br>        (address aggregator, bool outOfTimeRange) = _getValidationData(<br>            validationData<br>        );<br>        if (expectedAggregator != aggregator) {<br>            revert FailedOp(0, &quot;AA24 signature error&quot;);<br>        }<br>        if (outOfTimeRange) {<br>            revert FailedOp(0, &quot;AA22 expired or not due&quot;);<br>        }<br>        //pmAggregator is not a real signature aggregator: we don&#39;t have logic to handle it as address.<br>        // non-zero address means that the paymaster fails due to some signature check (which is ok only during estimation)<br>        address pmAggregator;<br>        (pmAggregator, outOfTimeRange) = _getValidationData(<br>            paymasterValidationData<br>        );<br>        if (pmAggregator != address(0)) {<br>            revert FailedOp(0, &quot;AA34 signature error&quot;);<br>        }<br>        if (outOfTimeRange) {<br>            revert FailedOp(0, &quot;AA32 paymaster expired or not due&quot;);<br>        }<br>    }<br><br>    function _validatePrepayment(<br>        UserOperation calldata userOp,<br>        UserOpInfo memory outOpInfo<br>    ) public returns (uint256 validationData, uint256 paymasterValidationData) {<br>        uint256 preGas = gasleft();<br>        MemoryUserOp memory mUserOp = outOpInfo.mUserOp;<br>        _copyUserOpToMemory(userOp, mUserOp);<br>        outOpInfo.userOpHash = getUserOpHash(userOp);<br>        uint256 maxGasValues = mUserOp.preVerificationGas |<br>            mUserOp.verificationGasLimit |<br>            mUserOp.callGasLimit |<br>            userOp.maxFeePerGas |<br>            userOp.maxPriorityFeePerGas;<br>        require(maxGasValues &lt;= type(uint120).max, &quot;AA94 gas values overflow&quot;);<br>        uint256 gasUsedByValidateAccountPrepayment;<br>        uint256 requiredPreFund = _getRequiredPrefund(mUserOp);<br>        (<br>            gasUsedByValidateAccountPrepayment,<br>            validationData<br>        ) = _validateAccountPrepayment(userOp, outOpInfo, requiredPreFund);<br><br>        if (!_validateAndUpdateNonce(mUserOp.sender, mUserOp.nonce)) {<br>            revert FailedOp(0, &quot;AA25 invalid account nonce&quot;);<br>        }<br><br>        //a &quot;marker&quot; where account opcode validation is done and paymaster opcode validation is about to start<br>        // (used only by off-chain simulateValidation)<br>        numberMarker();<br>        bytes memory context;<br>        if (mUserOp.paymaster != address(0)) {<br>            (context, paymasterValidationData) = _validatePaymasterPrepayment(<br>                userOp,<br>                outOpInfo,<br>                requiredPreFund,<br>                gasUsedByValidateAccountPrepayment<br>            );<br>        }<br>        unchecked {<br>            uint256 gasUsed = preGas - gasleft();<br>            if (userOp.verificationGasLimit &lt; gasUsed) {<br>                revert FailedOp(0, &quot;AA40 over verificationGasLimit&quot;);<br>            }<br>            outOpInfo.prefund = requiredPreFund;<br>            outOpInfo.contextOffset = getOffsetOfMemoryBytes(context);<br>            outOpInfo.preOpGas = preGas - gasleft() + userOp.preVerificationGas;<br>        }<br>    }<br>}</pre><h3>PaymasterV7 Contract</h3><p>The added code in the contracts\07_PaymasterV7.sol contract introduces functionalities for verifying user operations and managing prepayments. It leverages cryptographic signatures for validation, incorporates gas cost calculations, and facilitates interaction with the EntryPoint contract for depositing and withdrawing funds. Additionally, it implements methods for parsing paymaster data, handling post-operation actions, and managing contract deposits.</p><pre>// SPDX-License-Identifier: UNLICENSED<br>pragma solidity ^0.8.20;<br><br>// Uncomment this line to use console.log<br>// import &quot;hardhat/console.sol&quot;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/cryptography/ECDSA.sol&quot;;<br>import &quot;./libraries/UserOperationV7.sol&quot;;<br>import &quot;./interface/IEntryPoint_with_paymaster.sol&quot;;<br><br>contract VerifyingPaymasterV7 is Ownable {<br>    using MessageHashUtils for bytes32;<br>    using ECDSA for bytes32;<br>    using UserOperationLib for UserOperation;<br><br>    address public immutable verifyingSigner;<br>    uint256 private constant VALID_TIMESTAMP_OFFSET = 20;<br><br>    uint256 private constant SIGNATURE_OFFSET = 84;<br>    mapping(address =&gt; uint256) public senderNonce;<br><br>    enum PostOpMode {<br>        opSucceeded, // user op succeeded<br>        opReverted, // user op reverted. still has to pay for gas.<br>        postOpReverted //user op succeeded, but caused postOp to revert. Now it&#39;s a 2nd call, after user&#39;s op was deliberately reverted.<br>    }<br>    IEntryPoint public immutable _entryPoint;<br><br>    constructor(<br>        IEntryPoint _entryPointValue,<br>        address _verifyingSigner<br>    ) Ownable(_verifyingSigner) {<br>        verifyingSigner = _verifyingSigner;<br>        _entryPoint = _entryPointValue;<br>    }<br><br>    function _requireFromEntryPoint() internal virtual {<br>        require(msg.sender == address(_entryPoint), &quot;Sender not EntryPoint&quot;);<br>    }<br><br>    function entryPoint() public view virtual returns (IEntryPoint) {<br>        return _entryPoint;<br>    }<br><br>    function _payPrefund(uint256 missingAccountFunds) public virtual {<br>        if (missingAccountFunds != 0) {<br>            (bool success, ) = payable(msg.sender).call{<br>                value: missingAccountFunds,<br>                gas: type(uint256).max<br>            }(&quot;&quot;);<br>            (success);<br>            //ignore failure (its EntryPoint&#39;s job to verify, not account.)<br>        }<br>    }<br><br>    function pack(<br>        UserOperation calldata userOp<br>    ) internal pure returns (bytes memory ret) {<br>        // lighter signature scheme. must match UserOp.ts#packUserOp<br>        bytes calldata pnd = userOp.paymasterAndData;<br>        // copy directly the userOp from calldata up to (but not including) the paymasterAndData.<br>        // this encoding depends on the ABI encoding of calldata, but is much lighter to copy<br>        // than referencing each field separately.<br>        assembly {<br>            let ofs := userOp<br>            let len := sub(sub(pnd.offset, ofs), 32)<br>            ret := mload(0x40)<br>            mstore(0x40, add(ret, add(len, 32)))<br>            mstore(ret, len)<br>            calldatacopy(add(ret, 32), ofs, len)<br>        }<br>    }<br><br>    function anotherPack(<br>        UserOperation calldata userOp<br>    ) internal pure returns (bytes memory ret) {<br>        address sender = userOp.sender;<br>        uint256 nonce = userOp.nonce;<br>        bytes32 hashCallData = calldataKeccak(userOp.callData);<br>        uint256 callGasLimit = userOp.callGasLimit;<br>        uint256 verificationGasLimit = userOp.verificationGasLimit;<br>        uint256 preVerificationGas = userOp.preVerificationGas;<br>        uint256 maxFeePerGas = userOp.maxFeePerGas;<br>        uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;<br><br>        return<br>            abi.encode(<br>                sender,<br>                nonce,<br>                hashCallData,<br>                callGasLimit,<br>                verificationGasLimit,<br>                preVerificationGas,<br>                maxFeePerGas,<br>                maxPriorityFeePerGas<br>            );<br>    }<br><br>    function calldataKeccak(<br>        bytes calldata data<br>    ) internal pure returns (bytes32 ret) {<br>        assembly {<br>            let mem := mload(0x40)<br>            let len := data.length<br>            calldatacopy(mem, data.offset, len)<br>            ret := keccak256(mem, len)<br>        }<br>    }<br><br>    function _packValidationData(<br>        bool sigFailed,<br>        uint48 validUntil,<br>        uint48 validAfter<br>    ) public pure returns (uint256) {<br>        return<br>            (sigFailed ? 1 : 0) |<br>            (uint256(validUntil) &lt;&lt; 160) |<br>            (uint256(validAfter) &lt;&lt; (160 + 48));<br>    }<br><br>    function getHash(<br>        UserOperation calldata userOp,<br>        uint48 validUntil,<br>        uint48 validAfter<br>    ) public view returns (bytes32 hash) {<br>        //can&#39;t use userOp.hash(), since it contains also the paymasterAndData itself.<br>        hash = keccak256(<br>            abi.encode(<br>                anotherPack(userOp),<br>                block.chainid,<br>                address(this),<br>                senderNonce[userOp.getSender()],<br>                validUntil,<br>                validAfter<br>            )<br>        );<br>    }<br><br>    function validatePaymasterUserOp(<br>        UserOperation calldata userOp,<br>        bytes32 userOpHash,<br>        uint256 maxCost<br>    ) external returns (bytes memory context, uint256 validationData) {<br>        (userOpHash);<br>        _requireFromEntryPoint();<br>        return _validatePaymasterUserOp(userOp, maxCost);<br>    }<br><br>    function _validatePaymasterUserOp(<br>        UserOperation calldata userOp,<br>        uint256 maxCost<br>    ) public returns (bytes memory context, uint256 validationData) {<br>        (<br>            uint48 validUntil,<br>            uint48 validAfter,<br>            bytes calldata signature<br>        ) = parsePaymasterAndData(userOp.paymasterAndData);<br>        //ECDSA library supports both 64 and 65-byte long signatures.<br>        // we only &quot;require&quot; it here so that the revert reason on invalid signature will be of &quot;VerifyingPaymaster&quot;, and not &quot;ECDSA&quot;<br>        require(<br>            signature.length == 64 || signature.length == 65,<br>            &quot;VerifyingPaymaster: invalid signature length in paymasterAndData&quot;<br>        );<br>        bytes32 hash = getHash(userOp, validUntil, validAfter)<br>            .toEthSignedMessageHash();<br>        senderNonce[userOp.getSender()]++;<br>        //don&#39;t revert on signature failure: return SIG_VALIDATION_FAILED<br>        if (verifyingSigner != ECDSA.recover(hash, signature)) {<br>            return (&quot;&quot;, _packValidationData(true, validUntil, validAfter));<br>        }<br>        _payPrefund(maxCost);<br>        //no need for other on-chain validation: entire UserOp should have been checked<br>        // by the external service prior to signing it.<br>        return (&quot;&quot;, _packValidationData(false, validUntil, validAfter));<br>    }<br><br>    function parsePaymasterAndData(<br>        bytes calldata paymasterAndData<br>    )<br>        public<br>        pure<br>        returns (uint48 validUntil, uint48 validAfter, bytes calldata signature)<br>    {<br>        (validUntil, validAfter) = abi.decode(<br>            paymasterAndData[VALID_TIMESTAMP_OFFSET:SIGNATURE_OFFSET],<br>            (uint48, uint48)<br>        );<br>        signature = paymasterAndData[SIGNATURE_OFFSET:];<br>    }<br><br>    function postOp(<br>        PostOpMode mode,<br>        bytes calldata context,<br>        uint256 actualGasCost<br>    ) external {<br>        _requireFromEntryPoint();<br>        _postOp(mode, context, actualGasCost);<br>    }<br><br>    function _postOp(<br>        PostOpMode mode,<br>        bytes calldata context,<br>        uint256 actualGasCost<br>    ) internal virtual {<br>        (mode, context, actualGasCost); // unused params<br>        // subclass must override this method if validatePaymasterUserOp returns a context<br>        revert(&quot;must override&quot;);<br>    }<br><br>    /**<br>     * check current account deposit in the entryPoint<br>     */<br>    function getDeposit() public view returns (uint256) {<br>        return entryPoint().balanceOf(address(this));<br>    }<br><br>    /**<br>     * deposit more funds for this account in the entryPoint<br>     */<br>    function addDeposit() public payable {<br>        entryPoint().depositTo{value: msg.value}(address(this));<br>    }<br><br>    function withdrawDepositTo(<br>        address payable withdrawAddress,<br>        uint256 amount<br>    ) public onlyOwner {<br>        entryPoint().withdrawTo(withdrawAddress, amount);<br>    }<br><br>    receive() external payable {<br>        // React to receiving ether<br>    }<br>}</pre><p>The development involves integrating functionalities for validating user operations, managing prepayments, and handling gas calculations within the EntryPoint and Paymaster contracts. These additions enable secure and efficient execution of user transactions while ensuring proper management of funds and gas costs.</p><h3>Conclusion</h3><h3>Building for the Future: Wrapping Up Iteration 7 of Our Smart Contract Wallet</h3><p>Iteration 7 has been a game-changer for our Smart Contract Wallet, paving the way for a more user-friendly and efficient future! This time, we focused on introducing the revolutionary concept of gasless transactions.</p><h3>Introducing the Paymaster: Powering a Gasless Future</h3><p>The centerpiece of this update is the innovative Paymaster contract. This groundbreaking addition allows users to bypass gas fees entirely, both within the wallet and when interacting with smart contracts. Imagine the possibilities of seamless transactions without any upfront costs!</p><h3>Seamless Integration for a Powerful Future</h3><p>To seamlessly integrate the Paymaster into our architecture, we’ve made key modifications:</p><ul><li><strong>Enhanced UserOperation Structure</strong>: We’ve included a new field named paymasterAndData within the UserOperation structure. This provides a robust framework for smooth interaction with the Paymaster contract.</li><li><strong>Adapting the Entrypoint</strong>: The Entrypoint contract has been updated to handle paymaster-related parameters effectively. Additionally, it now incorporates the _payPrefund function from the Paymaster, enabling deposits and withdrawals from the entry point.</li><li><strong>Empowering the Paymaster Contract</strong>: The Paymaster contract itself comes equipped with features like validatePaymasterUserOp and parsePaymasterAndData. These functionalities ensure proper validation and parsing of paymaster data.</li></ul><h3>Continuous Improvement: Looking Ahead</h3><p>While iteration 7 marks a significant leap forward, we remain committed to continuous improvement:</p><ul><li><strong>Enhanced Paymaster Handling</strong>: We’ll be focusing on refining our system’s ability to handle various types of paymasters, ensuring broader compatibility.</li><li><strong>Codebase Optimization</strong>: Further codebase optimization is planned to enhance efficiency and performance.</li><li><strong>Expanding the Ecosystem</strong>: We welcome contributions in the form of pull requests for bundler implementations and additional paymaster contracts. This collaborative approach will further enhance the flexibility and usability of our platform. Thank you for joining us on this journey! We’re excited to explore the possibilities of gasless transactions and build a future where everyone can participate in DeFi with ease. Stay tuned for what’s next!</li></ul><h3>Code Repository and Continued Learning</h3><p>For a comprehensive overview of the concepts and techniques discussed in this series, along with the complete code examples used throughout the tutorials, please refer to the dedicated GitHub repository:</p><ul><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration">Demistifying-Account-Abstraction-A-Step-by-Step-Exploration</a></li></ul><p>This repository will serve as a valuable companion resource, allowing you to not only follow along with the code demonstrations but also explore the codebase in your own time. The repository will be continually updated as the series progresses, ensuring you have access to the latest code iterations.</p><h3>Thank you for joining us on this exploration!</h3><p>To delve deeper and contribute to the ongoing development, we encourage you to star our project’s <a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration">GitHub repository</a>. There, you can find valuable resources and raise Pull Requests (PRs) to address any issues or propose improvements. Let’s build a better blockchain UI together!</p><h3>References</h3><p>If you’d like to explore related topics in more depth, consider the below references</p><ol><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration/blob/main/docs/contracts/07_EntryPointV7.sol">EntryPointV7</a></li><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration/blob/main/docs/contracts/07_WalletV7.sol">WalletV7.sol</a></li><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration/blob/main/docs/test/07_WalletV7.test.js">Test file</a></li><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration/blob/main/docs/contracts/07_PaymasterV7.sol">PaymasterV7</a></li><li><a href="https://github.com/lakshyakumar/Demistifying-Account-Abstraction-A-Step-by-Step-Exploration/blob/main/docs/contracts/libraries/UserOperationV7.sol">UserOperationV7</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cdbc70b595b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>