<?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 Adenigba Olumide on Medium]]></title>
        <description><![CDATA[Stories by Adenigba Olumide on Medium]]></description>
        <link>https://medium.com/@maylord?source=rss-2e07889334d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-SrsndpPlnMVjtHA</url>
            <title>Stories by Adenigba Olumide on Medium</title>
            <link>https://medium.com/@maylord?source=rss-2e07889334d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:15:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maylord/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[Engineering the Counterfactual Explorer: How TwinOS Searches for Better Business Decisions]]></title>
            <link>https://maylord.medium.com/engineering-the-counterfactual-explorer-how-twinos-searches-for-better-business-decisions-4766ae4ee076?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4766ae4ee076</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 11:44:46 GMT</pubDate>
            <atom:updated>2026-06-24T11:44:46.386Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From deterministic forecasting to practical optimization for small and medium-sized businesses</strong></p><p><strong>Series:</strong> Building TwinOS, Part 3 of 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBMgThSr0K37gjUkxs4J5Q.jpeg" /><figcaption><em>The Counterfactual Explorer searches for practical operational changes that can move a business toward a target.</em></figcaption></figure><p>Most business software answers one of two questions:</p><p>1. What happened?</p><p>2. What might happen next?</p><p>TwinOS was built to answer a third:</p><blockquote><strong>What should I change to reach a specific outcome?</strong></blockquote><p>That question led to the <strong>Counterfactual Explorer</strong>, the optimization system at the heart of TwinOS.</p><p>A business owner does not always know which scenario to test. They may know only the goal:</p><p>- Increase profit by 30%</p><p>- Grow revenue by 15%</p><p>- Reduce stockout risk</p><p>- Improve employee capacity</p><p>- Reach a target while avoiding additional hires</p><p>The Counterfactual Explorer takes that target and searches for a practical set of operational changes.</p><p>It is not a chatbot inventing business advice. It is a deterministic simulation and search pipeline, with AI used afterward to explain the result in plain language.</p><p>This article explains how the model works, why I chose hill climbing for the first version, how I penalize disruptive changes, how AWS supports the search process, and where the engine goes next.</p><p><strong>Forward simulation versus counterfactual optimization</strong></p><p>A normal scenario simulator works in the forward direction.</p><p>The user provides changes:</p><pre>Price: +5%<br>Marketing: +$300<br>Headcount: +1</pre><p>The engine returns projected results:</p><pre>Revenue: +8.2%<br>Profit: +2.1%<br>Capacity: +14%<br>Stockout risk: +3%</pre><p>Counterfactual optimization reverses the direction.</p><p>The user provides a desired result:</p><pre>Target: Increase profit by 20%<br>Constraint: Avoid hiring</pre><p>The engine searches for inputs that may satisfy it:</p><pre>Price: +4%<br>Marketing: +$150<br>Headcount: unchanged</pre><p>This is an inverse problem.</p><p>The forward simulation is still essential because the optimizer calls it repeatedly. The optimization algorithm does not have a separate understanding of the business. It proposes a candidate, runs the deterministic simulator, evaluates the result, and decides where to search next.</p><p><strong>Representing the business baseline</strong></p><p>Every optimization run begins with a baseline state.</p><p>A simplified state vector might be:</p><pre>type BusinessState = {<br>monthlyUnitsSold: number;<br>averageUnitPrice: number;<br>averageUnitCost: number;<br>monthlyMarketingSpend: number;<br>monthlyFixedCosts: number;<br>employeeCount: number;<br>monthlyCostPerEmployee: number;<br>monthlyCapacityPerEmployee: number;<br>availableInventoryUnits: number;<br>demandElasticity: number;<br>};</pre><p>The baseline must be versioned.</p><p>If a user synchronizes new QuickBooks or Square data, the underlying business state changes. A forecast computed against the old baseline should not be treated as current.</p><p>A cache key can therefore include:</p><ul><li>Business ID</li><li>Baseline version</li><li>Scenario parameters</li><li>Forecast horizon</li><li>Engine version</li></ul><p>That prevents the optimizer from reusing a result generated from stale assumptions.</p><p><strong>Representing a candidate plan</strong></p><p>The optimizer does not alter the baseline directly. It creates candidate adjustments.</p><pre>type CandidatePlan = {<br>priceAdjustmentPct: number;<br>marketingDelta: number;<br>headcountDelta: number;<br>supplierDelayDays: number;<br>};</pre><p>A candidate becomes a simulated state by applying its changes to the baseline.</p><p>This separation is useful because it preserves:</p><ul><li>The original business data</li><li>The proposed action</li><li>The generated outcome</li><li>The ability to compare multiple candidates</li></ul><p>It also makes the algorithm easier to test.</p><p><strong>The deterministic simulation layer</strong></p><p>The simulation engine is deliberately deterministic.</p><p>Given the same baseline, candidate plan, horizon, and engine version, it should produce the same result.</p><p>That property makes the system:</p><ul><li>Testable</li><li>Cacheable</li><li>Explainable</li><li>Easier to debug</li></ul><p>The formulas are simplified business models, not promises of certainty. Their purpose is to expose trade-offs consistently.</p><p><strong>Demand and price elasticity</strong></p><p>A price increase usually affects demand.</p><p>A simplified demand multiplier can be expressed as:</p><pre>Demand Multiplier = 1 + (Price Change × Demand Elasticity)</pre><p>For example:</p><pre>Price change = +0.08<br>Elasticity = -0.60<br>Demand multiplier = 1 + (0.08 × -0.60)<br>= 0.952</pre><p>That represents an estimated 4.8% decline in unit demand after an 8% price increase.</p><p>In code:</p><pre>function calculateDemandMultiplier(<br>priceAdjustmentPct: number,<br>demandElasticity: number<br>): number {<br>const multiplier =<br>1 + priceAdjustmentPct * demandElasticity;<br>return Math.max(multiplier, 0);<br>}</pre><p>The lower bound avoids negative demand.</p><p>A more advanced model would support:</p><ul><li>Industry-specific elasticity</li><li>Product-level elasticity</li><li>Nonlinear price response</li><li>Seasonal effects</li><li>Customer segments</li><li>Confidence intervals</li></ul><p>For the hackathon MVP, the simpler model is easier to explain and validate.</p><p><strong>Marketing response</strong></p><p>Marketing does not turn directly into revenue. It changes expected demand.</p><p>A simple model can use diminishing returns:</p><pre>Marketing Lift = coefficient × log(1 + new spend / baseline spend)</pre><p>This is more realistic than assuming that doubling marketing always doubles demand.</p><p>A TypeScript example:</p><pre>function calculateMarketingLift(baselineSpend: number, newSpend: number, coefficient = 0.08<br>): number {<br>if (baselineSpend &lt;= 0) {<br>return newSpend &gt; 0 ? coefficient : 0;<br>}<br>const ratio = newSpend / baselineSpend;<br>return coefficient * Math.log1p(Math.max(ratio, 0));<br>}</pre><p>The coefficient should ultimately be learned or calibrated from business history. In the MVP, it is a configurable assumption.</p><p><strong>Revenue projection</strong></p><p>A simplified monthly revenue projection combines:</p><ul><li>Baseline units sold</li><li>Demand response</li><li>Marketing lift</li><li>New price</li><li>Seasonal factor</li></ul><pre>Projected Units =<br>Baseline Units<br>× Demand Multiplier<br>× (1 + Marketing Lift)<br>× Seasonal Factor</pre><pre>Projected Revenue =<br>Projected Units<br>× Adjusted Unit Price</pre><p><strong>Profit projection</strong></p><p>Profit includes variable and fixed costs.</p><pre>Gross Margin = Projected Revenue − Variable Product Cost<br><br>Projected Profit = Gross Margin − Payroll − Marketing − Fixed Costs − Delay or Risk Costs</pre><p>A simplified function:</p><pre>function projectProfit( baseline: BusinessState, candidate: CandidatePlan) {<br>const revenue = projectRevenue( baseline, candidate);<br><br>const employeeCount = Math.max( baseline.employeeCount + candidate.headcountDelta,<br>0 );<br>const payroll = employeeCount * baseline.monthlyCostPerEmployee;<br>const variableCost = revenue.projectedUnits * baseline.averageUnitCost;<br>const delayPenalty = candidate.supplierDelayDays * 25; // configurable model input<br>const projectedProfit = revenue.projectedRevenue - variableCost - payroll -<br>revenue.adjustedMarketing - baseline.monthlyFixedCosts - delayPenalty;<br><br>return {<br>…revenue,<br>employeeCount,<br>payroll,<br>variableCost,<br>projectedProfit,<br>};<br>}</pre><p>The real implementation can be more nuanced, but the principle remains: every recommendation must pass through the same accounting logic.</p><p><strong>Employee capacity</strong></p><p>Revenue growth is not useful if the business cannot serve the demand.</p><p>TwinOS estimates capacity by comparing expected workload with available labor capacity.</p><pre>Available Capacity = Employee Count × Capacity Per Employee\<br><br>Capacity Utilization = Projected Demand ÷ Available Capacity</pre><p>A value above `1.0` suggests expected demand exceeds modeled capacity.</p><p>The optimizer can reject candidates whose utilization exceeds a safety threshold. That prevents the engine from recommending a plan that raises revenue only by overwhelming the team.</p><p><strong>Inventory and stockout risk</strong></p><p>A simplified inventory ratio is:</p><pre>Coverage Ratio = Available Inventory ÷ Projected Demand</pre><p>Stockout risk rises as coverage falls.</p><p>A simple risk mapping:</p><pre>function calculateStockoutRisk(<br>availableInventory: number,<br>projectedUnits: number,<br>supplierDelayDays: number<br>): number {<br>if (projectedUnits &lt;= 0) return 0;<br>const delayFactor =<br>1 + supplierDelayDays / 30;<br>const requiredInventory =<br>projectedUnits * delayFactor;<br>const coverage =<br>availableInventory /<br>requiredInventory;<br>return Math.min(<br>Math.max(1 - coverage, 0),<br>1<br>);<br>}</pre><p>This is not a supply-chain oracle. It is a consistent signal that lets the user see when an apparently profitable plan increases operational risk.</p><p><strong>## Defining the optimization objective</strong></p><p>Suppose the user requests:</p><pre>Target metric: Profit<br>Target increase: 30%</pre><p>The baseline profit is:</p><pre>$30,000/month</pre><p>The target becomes:</p><pre>$39,000/month</pre><p>A candidate is successful if:</p><pre>Projected profit &gt;= $39,000</pre><p>However, multiple candidates may satisfy the goal.</p><p>TwinOS therefore needs to prefer the least disruptive successful plan.</p><p>The score can combine:</p><ul><li>Target achievement</li><li>Distance from the target</li><li>Constraint violations</li><li>Operational change cost</li></ul><p>A simplified score:</p><pre>Score = Target Achievement Reward − Change Cost − Constraint Penalty</pre><p>The optimizer tries to maximize this score.</p><p><strong>Penalizing operational disruption</strong></p><p>This is one of the most important design decisions in the engine.</p><p>The mathematically best plan may be absurd in the real world.</p><p>A candidate that removes three employees, doubles prices, and eliminates marketing might produce a strong short-term number in a simplistic model. It would also damage the business.</p><p>TwinOS assigns different weights to different changes.</p><p>An example change-cost function:</p><pre>Change Cost = (Price Change)² × 1.0 + (Headcount Change)² × 5.0 + (Marketing Change / 1000)² × 1.5</pre><p>A TypeScript implementation:</p><pre>function calculateChangeCost(<br>candidate: CandidatePlan<br>): number {<br>const priceWeight = 1.0;<br>const headcountWeight = 5.0;<br>const marketingWeight = 1.5;<br>const delayWeight = 0.5;<br>return (<br>Math.pow(<br>candidate.priceAdjustmentPct * 100,<br>2<br>) * priceWeight +<br>Math.pow(<br>candidate.headcountDelta,<br>2<br>) * headcountWeight +<br>Math.pow(<br>candidate.marketingDelta / 1000,<br>2<br>) * marketingWeight +<br>Math.pow(<br>candidate.supplierDelayDays,<br>2<br>) * delayWeight<br>);<br>}</pre><p>The exact weights are product assumptions. In the future, they can be adjusted by industry or user preference.</p><p>For example, a consultancy may treat headcount changes differently from a restaurant.</p><p><strong>Why hill climbing was a good MVP algorithm</strong></p><p>The search space can grow quickly.</p><p>If TwinOS tests:</p><p>- 21 possible price adjustments</p><p>- 11 headcount values</p><p>- 31 marketing adjustments</p><p>- 8 supplier-delay values</p><p>the naive grid already contains:</p><pre>21 × 11 × 31 × 8 = 57,288 candidates</pre><p>Add more parameters and the space explodes.</p><p>For the first version, I chose hill climbing because it is:</p><ul><li>Simple to implement</li><li>Easy to explain</li><li>Fast enough for interactive use</li><li>Suitable for iterative improvement</li><li>Easy to instrument</li></ul><p>The process is:</p><p>1. Start at the current business state.</p><p>2. Generate neighboring candidates.</p><p>3. Simulate each neighbor.</p><p>4. Select the best-scoring candidate.</p><p>5. Move to that candidate.</p><p>6. Repeat until no meaningful improvement remains or a limit is reached.</p><p><strong>Generating neighbors</strong></p><p>A neighbor changes one or more parameters by a small step.</p><p>For example:</p><pre>function generateNeighbors(<br>current: CandidatePlan<br>): CandidatePlan[] {<br>const priceSteps = [-0.01, 0.01];<br>const marketingSteps = [-100, 100];<br>const headcountSteps = [-1, 1];<br>const neighbors: CandidatePlan[] = [];<br>for (const step of priceSteps) {<br>neighbors.push({<br>…current,<br>priceAdjustmentPct:<br>current.priceAdjustmentPct + step,<br>});<br>}<br>for (const step of marketingSteps) {<br>neighbors.push({<br>…current,<br>marketingDelta:<br>current.marketingDelta + step,<br>});<br>}<br>for (const step of headcountSteps) {<br>neighbors.push({<br>…current,<br>headcountDelta:<br>current.headcountDelta + step,<br>});<br>}<br>return neighbors.filter(isCandidateAllowed);<br>}</pre><p>The `isCandidateAllowed` function enforces hard limits, such as:</p><ul><li>Maximum price increase</li><li>Minimum headcount</li><li>Maximum marketing budget</li><li>Valid supplier-delay range</li></ul><p>Hard constraints prevent the algorithm from wasting time on impossible candidates.</p><p><strong>The limits of hill climbing</strong></p><p>Hill climbing can become trapped in a local optimum.</p><p>Imagine the search landscape contains several hills. The algorithm climbs the nearest one, but a taller hill may exist elsewhere.</p><p>That is acceptable for an MVP when:</p><p>- The search must remain fast</p><p>- The parameter space is constrained</p><p>- The result is a recommendation, not an autonomous decision</p><p>- The system clearly explains its assumptions</p><p>Future versions of TwinOS will reduce this limitation with:</p><p>- Multiple random starts</p><p>- Simulated annealing</p><p>- Beam search</p><p>- Genetic algorithms</p><p>- Hybrid search strategies</p><p><strong>Why genetic algorithms are a natural next step</strong></p><p>A genetic algorithm represents candidate plans as a population.</p><p>Each generation:</p><p>1. Evaluates candidate fitness</p><p>2. Selects stronger candidates</p><p>3. Combines them</p><p>4. Mutates some parameters</p><p>5. Repeats</p><p>This approach can search a larger and less smooth space than basic hill climbing.</p><p>It is especially useful when TwinOS adds:</p><ul><li>Product-level pricing</li><li>Multiple locations</li><li>Shift schedules</li><li>Supplier choices</li><li>Inventory policies</li><li>Several simultaneous targets</li></ul><p><strong>Multi-objective optimization</strong></p><p>Businesses rarely optimize one number.</p><p>An owner may want:</p><ul><li>Higher profit</li><li>Stable headcount</li><li>Lower stockout risk</li><li>No more than a 5% price increase</li></ul><p>These objectives may conflict.</p><p>A future TwinOS engine can produce a Pareto frontier: a set of plans where no objective can improve without making another worse.</p><p>Instead of presenting one answer, TwinOS could present:</p><ul><li>Highest-profit plan</li><li>Lowest-disruption plan</li><li>Lowest-risk plan</li><li>Balanced plan</li></ul><p>That is closer to how real decisions are made.</p><p><strong>## Deterministic engine, AI explanation</strong></p><p>The Counterfactual Explorer uses AI, but not as the calculator.</p><p>The simulation and optimization outputs are structured:</p><pre>{<br>&quot;target&quot;: {<br>&quot;metric&quot;: &quot;profit&quot;,<br>&quot;increasePct&quot;: 30<br>},<br>&quot;recommendation&quot;: {<br>&quot;priceAdjustmentPct&quot;: 0.04,<br>&quot;marketingDelta&quot;: 150,<br>&quot;headcountDelta&quot;: 0<br>},<br>&quot;projected&quot;: {<br>&quot;revenue&quot;: 96000,<br>&quot;profit&quot;: 39500,<br>&quot;capacityUtilization&quot;: 0.88,<br>&quot;stockoutRisk&quot;: 0.12<br>},<br>&quot;assumptions&quot;: {<br>&quot;demandElasticity&quot;: -0.6,<br>&quot;horizonDays&quot;: 90<br>}<br>}</pre><p>The AI receives that result and produces an explanation.</p><p>A good explanation should:</p><ul><li>State what changed</li><li>State why the model expects the result</li><li>Mention the major trade-offs</li><li>Repeat important assumptions</li><li>Avoid presenting projections as certainty</li></ul><p>For example:</p><blockquote>TwinOS recommends a 4% price adjustment and a modest increase in marketing while keeping headcount unchanged. The model expects the additional gross margin to outweigh the projected decline in unit demand. Capacity remains below the configured threshold, and the inventory model does not indicate a material increase in stockout risk. This projection depends on the current demand-elasticity assumption and should be reviewed against actual performance.</blockquote><p>That is far more useful than “AI says raise your prices.”</p><p><strong>Using DynamoDB for optimization telemetry</strong></p><p>Every search run produces valuable debugging data.</p><p>TwinOS writes iteration records to DynamoDB so I can answer questions such as:</p><ul><li>How many iterations did the run require?</li><li>Which parameter changed most often?</li><li>Where did the score stop improving?</li><li>How much time was spent evaluating candidates?</li><li>Did a constraint reject most neighbors?</li><li>Which engine version produced the recommendation?</li></ul><p>A run can use:</p><pre>Partition key: runId<br>Sort key: iteration</pre><p>This makes it easy to retrieve the complete optimization path in order.</p><p>Telemetry also supports a better user experience. The frontend can show progress milestones such as:</p><pre>Evaluating pricing adjustments…<br>Testing workforce configurations…<br>Checking inventory constraints…<br>Comparing candidate plans…<br>Preparing recommendation…</pre><p>The loading state becomes an honest reflection of the search process.</p><p><strong>Caching completed forecasts</strong></p><p>The optimizer may evaluate the same candidate more than once, especially after future algorithm upgrades.</p><p>TwinOS uses a deterministic cache key based on:</p><ul><li>Baseline version</li><li>Candidate plan</li><li>Forecast horizon</li><li>Engine version</li></ul><p>Before calculating, the engine checks DynamoDB.</p><p>If the result exists and is still valid, it can reuse it.</p><p>This reduces computation and makes repeated runs faster.</p><p>Caching is safe because the simulation engine is deterministic for a fixed version and input set.</p><p><strong>## What the model does not know</strong></p><p>TwinOS is a decision-support tool, not a guarantee.</p><p>The current model may not know:</p><p>- A competitor is opening nearby</p><p>- A viral social post will increase demand</p><p>- A new regulation will affect costs</p><p>- Employee morale will change</p><p>- Customers will react differently from the assumed elasticity</p><p>- A supplier will fail entirely</p><p>That is why the interface should show:</p><p>- Assumptions</p><p>- Forecast horizon</p><p>- Sensitivity</p><p>- Risk warnings</p><p>- The difference between model output and observed reality</p><p>The model becomes more valuable when it is honest about uncertainty.</p><p><strong>What I learned building the Counterfactual Explorer</strong></p><p><strong><em>Optimization is a product-design problem</em></strong></p><p>An algorithm can find a mathematically strong answer that no human would use.</p><p>Weights, constraints, and explanation are part of the product.</p><p><strong><em>Explainability begins before the AI layer</em></strong></p><p>The engine must preserve the causal structure of the result. AI cannot explain a number honestly if the calculation path is opaque.</p><p><strong><em>Simple algorithms can create strong experiences</em></strong></p><p>Hill climbing is not the most advanced optimization method, but it is understandable, fast, and good enough to validate the product idea.</p><p><strong><em>Logging is not an afterthought</em></strong></p><p>Iteration telemetry made the optimizer easier to debug and the user experience easier to design.</p><p><strong><em>A business plan is a set of trade-offs</em></strong></p><p>TwinOS should not pretend there is one universally correct plan. The long-term opportunity is to help users compare several defensible futures.</p><p><strong>## The larger vision</strong></p><p>Today, the Counterfactual Explorer recommends a small set of pricing, marketing, staffing, and inventory changes.</p><p>The long-term vision is broader:</p><ul><li>Continuously synchronize real business data</li><li>Compare predicted outcomes with actual results</li><li>Recalibrate assumptions</li><li>Search more complex operational spaces</li><li>Support several simultaneous objectives</li><li>Let business partners collaborate on scenarios</li><li>Build industry-specific models</li><li>Explain every recommendation clearly</li></ul><p>The goal is not to automate judgment out of the business.</p><p>It is to give judgment a better instrument panel.</p><p>A pilot still flies the aircraft. The simulator lets them practice before the weather turns.</p><p>That is what TwinOS aims to do for small businesses.</p><p><strong>## Read the full series</strong></p><p>- <a href="https://maylord.medium.com/from-spreadsheet-guesswork-to-twinos-building-a-business-flight-simulator-for-smbs-6bfb52590104"><strong>Part 1:</strong> From Spreadsheet Guesswork to TwinOS</a></p><p>- <a href="https://maylord.medium.com/building-twinos-with-aws-aurora-dynamodb-prisma-and-vercel-ab3bc2424a02"><strong>Part 2:</strong> Building TwinOS with AWS Aurora, DynamoDB, Prisma, and Vercel</a></p><p><em>*I created this article for the purpose of entering the Hack the Zero Stack (H0) Hackathon. TwinOS was built using Vercel, v0, AWS Aurora PostgreSQL, Amazon DynamoDB, Next.js, Prisma, and Clerk. #H0Hackathon*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4766ae4ee076" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building TwinOS with AWS Aurora, DynamoDB, Prisma, and Vercel]]></title>
            <link>https://maylord.medium.com/building-twinos-with-aws-aurora-dynamodb-prisma-and-vercel-ab3bc2424a02?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab3bc2424a02</guid>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aurora]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 00:30:07 GMT</pubDate>
            <atom:updated>2026-06-23T00:30:07.774Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A technical deep dive into the cloud architecture behind an SMB business-simulation platform</strong></p><p><strong>Series:</strong> Building TwinOS, Part 2 of 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_GwFc8zUwxK_6X5jB278g.jpeg" /><figcaption><em>TwinOS combines Vercel’s application platform with Aurora for relational data and DynamoDB for cache and optimization telemetry</em></figcaption></figure><p>TwinOS began as a product idea: give small and medium-sized businesses a digital twin they can use to test operational decisions.</p><p>Turning that idea into a working full-stack application required a data architecture that could support two very different workloads.</p><p>The first workload is relational and transactional:</p><ul><li>Users</li><li>Workspaces</li><li>Businesses</li><li>Products</li><li>Employees</li><li>Scenarios</li><li>Forecasts</li><li>OAuth integrations</li><li>Workspace settings</li></ul><p>The second workload is high-volume and access-pattern driven:</p><ul><li>Forecast caching</li><li>Optimization telemetry</li><li>Iteration logs</li><li>Fast retrieval of previously computed results</li></ul><p>Trying to force both workloads into one database would have made the system simpler on paper and weaker in practice.</p><p>I therefore designed TwinOS around a hybrid AWS database architecture:</p><ul><li><strong>Amazon Aurora PostgreSQL</strong> as the primary relational database</li><li><strong>Amazon DynamoDB</strong> for forecast caching and optimization logs</li><li><strong>Vercel</strong> for the Next.js application and API layer</li><li><strong>Prisma ORM</strong> for typed access to relational data</li><li><strong>Clerk</strong> for identity and multi-tenant authentication</li></ul><p>This article explains how those pieces fit together, how I set up Aurora, how I moved from local SQLite development to PostgreSQL, how DynamoDB supports the simulation engine, and what I learned about deploying a database-backed Next.js application on Vercel.</p><p><strong>The architecture at a glance</strong></p><p>The request flow is straightforward:</p><p>1. The SMB owner interacts with the TwinOS interface.</p><p>2. The Next.js frontend sends JSON requests to server-side route handlers.</p><p>3. Clerk provides the authenticated user and workspace context.</p><p>4. Prisma reads and writes relational records in Aurora PostgreSQL.</p><p>5. DynamoDB stores forecast cache entries and optimization telemetry.</p><p>6. OAuth integrations synchronize data from QuickBooks, Shopify, and Square.</p><p>7. The frontend renders results with Recharts.</p><p>Conceptually:</p><pre>SMB Owner<br>|<br>v<br>Next.js on Vercel<br>|<br>+ → Clerk authentication<br>|<br>+ → Prisma → Aurora PostgreSQL<br>|<br>+ → AWS SDK → DynamoDB<br>|<br>+ → OAuth 2.0 → QuickBooks / Shopify / Square</pre><p>The architecture intentionally keeps the application layer cohesive. The same Next.js project serves the interface and the server-side APIs, while AWS provides durable data services.</p><p><strong>Why Aurora PostgreSQL is the system of record</strong></p><p>TwinOS data is naturally relational.</p><p>A workspace contains users and businesses. A business contains products and employees. Scenarios belong to businesses. Results belong to scenarios. Integration records belong to workspaces or businesses.</p><p>These relationships matter because the application frequently needs to answer questions such as:</p><ul><li>Which scenarios belong to this business?</li><li>Which products were included in this baseline?</li><li>Which employee assumptions were active when this forecast was created?</li><li>Which workspace owns this QuickBooks integration?</li><li>Which user is permitted to modify the business twin?</li></ul><p>PostgreSQL is well suited to these queries, and <strong>Aurora </strong>provides a managed PostgreSQL-compatible engine on <strong>AWS</strong>.</p><p>Aurora became the primary store for:</p><ul><li>Identity mappings</li><li>Tenant and workspace data</li><li>Business profiles</li><li>Products</li><li>Employees</li><li>Historical baseline metrics</li><li>Scenarios and scenario inputs</li><li>Simulation results</li><li>Integration metadata</li><li>Settings and permissions</li></ul><p>The most important architectural decision was not simply “use PostgreSQL.” It was to make Aurora the authoritative source of truth while keeping transient optimization data elsewhere.</p><p><strong>My Aurora setup process</strong></p><p>This was my first production-style Aurora deployment, so I treated the setup as both an implementation task and a learning exercise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7uuXa6TKUh_Swvtcb8vvw.jpeg" /><figcaption><em>The production TwinOS relational database runs on an Aurora PostgreSQL-compatible cluster.</em></figcaption></figure><p><strong>1. Choosing the database engine</strong></p><p>I created an Aurora PostgreSQL-compatible cluster.</p><p>PostgreSQL compatibility mattered because the local data model was already built around relational constraints and Prisma. It let me preserve familiar SQL semantics while moving to managed AWS infrastructure.</p><p><strong>2. Creating the cluster and credentials</strong></p><p>During cluster creation, I configured:</p><ul><li>A database cluster identifier</li><li>A master database user</li><li>A secure password</li><li>The PostgreSQL-compatible engine version</li><li>The desired region</li><li>Capacity appropriate for the hackathon workload</li></ul><p>Credentials were never committed to source control. They were stored as environment variables for local development and in Vercel project settings for deployment.</p><p>A typical connection variable has the shape:</p><pre>DATABASE_URL=&quot;postgresql://USER:PASSWORD@DATABASENAME.clusterID.AWSREGION.rds.amazonaws.com:5432/postgres?schema=public&quot;</pre><p>The actual value remains secret.</p><p><strong>3. Configuring network access</strong></p><p>Database connectivity was one of the most instructive parts of the build.</p><p>Aurora lives inside AWS networking, while the TwinOS application runs on Vercel. That means the application needs a secure, intentional path to the database endpoint.</p><p>I configured the database networking and security rules to allow the required application connectivity while avoiding broad, unnecessary access.</p><p>For a production hardening pass, I would further tighten the design with measures such as:</p><ul><li>Private subnets where appropriate</li><li>Restricted security-group rules</li><li>A controlled proxy or connection-pooling layer</li><li>Secret rotation</li><li>Separate credentials per environment</li><li>Stronger network isolation between preview and production workloads</li></ul><p>The important lesson was that creating a database is only half the work. Connectivity, trust boundaries, and credential handling are part of the database architecture.</p><p><strong>4. Confirming the endpoint and connectivity</strong></p><p>After the cluster became available, I used the Aurora endpoint in the PostgreSQL connection string and tested the connection before deploying schema changes.</p><p>Useful checks included:</p><ul><li>DNS resolution</li><li>Port connectivity</li><li>Authentication</li><li>SSL requirements</li><li>Correct database name</li><li>Correct Prisma provider</li></ul><p><strong>5. Running the Prisma workflow</strong></p><p>Once connectivity worked, the deployment workflow was:</p><pre>pnpm prisma generate<br>pnpm prisma migrate deploy</pre><p>For development environments, I could use:</p><pre>pnpm prisma migrate dev</pre><p>The production deployment uses migration files already committed to the repository. This makes schema changes reviewable and repeatable.</p><p><strong>Moving from SQLite to Aurora PostgreSQL</strong></p><p>For fast local development, TwinOS initially used SQLite.</p><p>SQLite was useful because it required almost no infrastructure. It allowed me to validate the schema, build CRUD operations, and iterate on the product before cloud setup was complete.</p><p>However, SQLite and PostgreSQL are not identical. Moving between them can expose differences in:</p><ul><li>Column types</li><li>Defaults</li><li>JSON handling</li><li>Enums</li><li>Index behavior</li><li>Concurrency</li><li>Migration syntax</li></ul><p>I created a small database-switching workflow so the local project could move between a lightweight sandbox and the production PostgreSQL provider.</p><p>Conceptually:</p><pre>node scripts/db-switch.js sqlite<br>node scripts/db-switch.js postgres</pre><p>The script updates the Prisma datasource configuration and regenerates the client.</p><p>A simplified Prisma datasource for PostgreSQL looks like:</p><pre>datasource db {<br>provider = &quot;postgresql&quot;<br>url = env(&quot;DATABASE_URL&quot;)<br>}</pre><p>The key lesson was to treat the database provider switch as a migration project, not a configuration toggle. I reviewed the schema, regenerated Prisma, applied migrations, and tested the most important queries against <strong>Aurora</strong>.</p><p><strong>A relational model for the digital twin</strong></p><p>A simplified portion of the TwinOS data model looks like this:</p><pre>model Business {<br>id String @id @default(cuid())<br>workspaceId String<br>name String<br>industry String?<br>products Product[]<br>employees Employee[]<br>scenarios Scenario[]<br>createdAt DateTime @default(now())<br>updatedAt DateTime @updatedAt<br>}<br>model Product {<br>id String @id @default(cuid())<br>businessId String<br>name String<br>price Decimal<br>unitCost Decimal<br>business Business @relation(fields: [businessId], references: [id], onDelete: Cascade)<br>}<br>model Employee {<br>id String @id @default(cuid())<br>businessId String<br>role String<br>monthlyCost Decimal<br>weeklyCapacity Decimal?<br>business Business @relation(fields: [businessId], references: [id], onDelete: Cascade)<br>}<br>model Scenario {<br>id String @id @default(cuid())<br>businessId String<br>name String<br>horizonDays Int<br>status String<br>inputJson Json<br>results SimulationResult[]<br>business Business @relation(fields: [businessId], references: [id], onDelete: Cascade)<br>createdAt DateTime @default(now())<br>}<br>model SimulationResult {<br>id String @id @default(cuid())<br>scenarioId String<br>projectedRevenue Decimal<br>projectedProfit Decimal<br>employeeCapacity Decimal?<br>stockoutRisk Decimal?<br>explanationJson Json?<br>scenario Scenario @relation(fields: [scenarioId], references: [id], onDelete: Cascade)<br>createdAt DateTime @default(now())<br>}</pre><p>The real schema can evolve, but the structure shows why a relational engine is valuable. Referential integrity is part of the product.</p><p>A result should not exist without a scenario. A scenario should not exist without a business. A user should not be able to read another workspace’s records.</p><p><strong>Multi-tenant authorization</strong></p><p>Clerk handles user authentication and session management, but authentication alone is not authorization.</p><p>TwinOS maps each request to a workspace or tenant and verifies ownership before touching data.</p><p>A simplified pattern looks like:</p><pre>const { userId, orgId } = await auth();<br>if (!userId || !orgId) {<br>return new Response(&quot;Unauthorized&quot;, { status: 401 });<br>}<br>const business = await prisma.business.findFirst({<br>where: {<br>id: businessId,<br>workspaceId: orgId,<br>},<br>});<br>if (!business) {<br>return new Response(&quot;Not found&quot;, { status: 404 });<br>}</pre><p>This pattern prevents a valid user from accessing a business that belongs to a different workspace.</p><p>Every data path needs the same discipline. Multi-tenancy cannot be bolted on at the end.</p><p><strong>Why DynamoDB has a separate role</strong></p><p>Aurora is the source of truth, but not every piece of simulation data belongs in a relational transaction.</p><p>The Counterfactual Explorer may evaluate hundreds of neighboring states during one optimization run. Each iteration can produce:</p><ul><li>Candidate parameters</li><li>Objective score</li><li>Constraint status</li><li>Change cost</li><li>Runtime metadata</li><li>Convergence information</li></ul><p>That data is valuable for debugging and performance analysis, but it does not need to become a deeply relational record.</p><p>DynamoDB fits this access pattern well because the application usually knows exactly what it wants:</p><ul><li>Retrieve a cached forecast by key</li><li>Read all telemetry for one optimization run</li><li>Store the latest result for a business and scenario configuration</li><li>Expire stale cache entries</li></ul><p>TwinOS uses two conceptual tables.</p><p><strong>ForecastCache</strong></p><p>Purpose:</p><ul><li>Avoid recomputing identical forecasts</li><li>Return repeat results quickly</li><li>Store normalized simulation output</li></ul><p>Possible keys:</p><pre>Partition key: cacheKey<br>Sort key: createdAt</pre><p>A `cacheKey` can be a deterministic hash of:</p><ul><li>Business baseline version</li><li>Scenario inputs</li><li>Forecast horizon</li><li>Simulation-engine version</li></ul><p>A simplified item:</p><pre>{<br>&quot;cacheKey&quot;: &quot;sha256:…&quot;,<br>&quot;createdAt&quot;: &quot;2026–06–20T14:00:00Z&quot;,<br>&quot;businessId&quot;: &quot;business_123&quot;,<br>&quot;horizonDays&quot;: 90,<br>&quot;engineVersion&quot;: &quot;1.0.0&quot;,<br>&quot;result&quot;: {<br>&quot;revenue&quot;: 96000,<br>&quot;profit&quot;: 39500,<br>&quot;capacity&quot;: 0.84,<br>&quot;stockoutRisk&quot;: 0.12<br>},<br>&quot;expiresAt&quot;: 1781964000<br>}</pre><p>The `expiresAt` value can support TTL-based cleanup when enabled.</p><p><strong>OptimizationRuns</strong></p><p>Purpose:</p><ul><li>Record search progress</li><li>Inspect convergence</li><li>Debug unexpected recommendations</li><li>Compare algorithm versions</li></ul><p>Possible keys:</p><pre>Partition key: runId<br>Sort key: iteration</pre><p>A simplified item:</p><pre>{<br>&quot;runId&quot;: &quot;opt_abc123&quot;,<br>&quot;iteration&quot;: 42,<br>&quot;businessId&quot;: &quot;business_123&quot;,<br>&quot;targetMetric&quot;: &quot;profit&quot;,<br>&quot;targetValue&quot;: 0.30,<br>&quot;candidate&quot;: {<br>&quot;priceAdjustment&quot;: 0.04,<br>&quot;headcountDelta&quot;: -1,<br>&quot;marketingDelta&quot;: 200<br>},<br>&quot;score&quot;: 0.917,<br>&quot;changeCost&quot;: 5.076,<br>&quot;createdAt&quot;: &quot;2026–06–20T14:02:11Z&quot;<br>}</pre><p>DynamoDB is not acting as a second source of truth. It is handling cache and telemetry workloads that benefit from predictable key-based access.</p><p><strong>OAuth integrations and encrypted tokens</strong></p><p>TwinOS integrates with external platforms to build a more accurate business baseline.</p><p>The architecture currently includes:</p><ul><li>QuickBooks for financial information</li><li>Shopify for product data</li><li>Square POS for labor or sales data</li></ul><p>OAuth 2.0 introduces several security responsibilities:</p><ul><li>State validation</li><li>Callback validation</li><li>Token exchange</li><li>Refresh-token handling</li><li>Revocation</li><li>Scope management</li><li>Secure storage</li></ul><p>Access and refresh tokens should never be stored as plain text.</p><p>TwinOS uses AES-256-GCM encryption before tokens are written to the database.</p><p>The encryption key belongs in the deployment secret store, not in the repository.</p><p>A future production hardening step would be to move key management into an AWS-managed key service and formalize rotation procedures.</p><p><strong>Deploying the Next.js application on Vercel</strong></p><p>Vercel provided the application layer for TwinOS.</p><p>The workflow was simple:</p><p>1. Push code to the connected Git repository.</p><p>2. Let Vercel create a preview deployment.</p><p>3. Test the application against the configured environment.</p><p>4. Promote the stable version to production.</p><p><strong>Serverless database connections</strong></p><p>A serverless application can create many short-lived function instances. Each instance opening database connections without control can exhaust the database.</p><p>This is an important production consideration for Prisma and PostgreSQL.</p><p>Mitigation options include:</p><ul><li>Reusing the Prisma client within a runtime instance</li><li>Applying sensible connection limits</li><li>Using a pooling or proxy solution</li><li>Avoiding unnecessary database round trips</li><li>Caching repeat simulation output</li><li>Monitoring active connections</li></ul><p>Production connection management still requires architecture appropriate to the deployed runtime.</p><p><strong>Why Vercel and AWS complement each other</strong></p><p>Vercel and AWS solve different parts of the problem.</p><p>Vercel gave TwinOS:</p><ul><li>Fast frontend deployment</li><li>Preview environments</li><li>Next.js-native hosting</li><li>Environment management</li><li>Global asset delivery</li><li>A clean developer workflow</li></ul><p>AWS gave TwinOS:</p><ul><li>A managed relational database</li><li>A high-speed key-value and document database</li><li>Durable cloud infrastructure</li><li>Clear paths for future scale and security hardening</li></ul><p>The application does not have to choose between frontend velocity and backend strength. The architecture combines them.</p><p><strong>Observability and operational lessons</strong></p><p>Even a hackathon application benefits from basic observability.</p><p>Useful signals include:</p><ul><li>API error rates</li><li>Database query failures</li><li>Simulation runtime</li><li>Cache hit rate</li><li>Optimization iteration count</li><li>OAuth refresh failures</li><li>DynamoDB fallback frequency</li><li>Aurora connection usage</li></ul><p>One of the most valuable future improvements would be a unified operational dashboard that shows the entire simulation path from request to stored result.</p><p><strong>What I learned from using AWS Aurora for the first time</strong></p><p><strong><em>Networking is part of application development</em></strong></p><p>A database endpoint is not automatically an application connection. Security groups, routing, credentials, SSL, and deployment origin all matter.</p><p><strong><em>Managed does not mean maintenance-free</em></strong></p><p>AWS manages much of the infrastructure, but the developer still owns:</p><ul><li>Schema design</li><li>Query efficiency</li><li>Connection behavior</li><li>Authorization</li><li>Secret handling</li><li>Backup and recovery choices</li></ul><p><strong><em>Two databases can be simpler than one when responsibilities are clear</em></strong></p><p>The hybrid architecture works because each service has a precise role.</p><ul><li>Aurora: durable relational source of truth</li><li>DynamoDB: cache and optimization telemetry</li></ul><p>Without that boundary, two databases would create confusion. With it, they reduce complexity.</p><p><strong><em>Cloud architecture should support the product, not decorate it</em></strong></p><p>The strongest technical decisions in TwinOS map directly to user experience:</p><ul><li>Cached forecasts reduce waiting.</li><li>Durable scenario history enables comparison.</li><li>Structured business data enables trustworthy simulations.</li><li>Encrypted integrations make live synchronization possible.</li><li>Preview deployments accelerate iteration.</li></ul><p>The current architecture is strong enough to demonstrate the product and explicit enough to evolve.</p><p>That was the goal.</p><p><strong>Continue the series</strong></p><p>- <a href="https://medium.com/@maylord/from-spreadsheet-guesswork-to-twinos-building-a-business-flight-simulator-for-smbs-6bfb52590104"><strong>Part 1:</strong>From Spreadsheet Guesswork to TwinOS</a></p><p>- <strong>Part 3:</strong> Engineering the Counterfactual Explorer</p><p><em>*I created this article for the purpose of entering the Hack the Zero Stack (H0) Hackathon. TwinOS was built using Vercel, v0, AWS Aurora PostgreSQL, Amazon DynamoDB, Next.js, Prisma, and Clerk. #H0Hackathon*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab3bc2424a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Spreadsheet Guesswork to TwinOS: Building a Business Flight Simulator for SMBs]]></title>
            <link>https://maylord.medium.com/from-spreadsheet-guesswork-to-twinos-building-a-business-flight-simulator-for-smbs-6bfb52590104?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bfb52590104</guid>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[product-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 23:39:34 GMT</pubDate>
            <atom:updated>2026-06-22T23:39:34.341Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How v0, Next.js, Vercel, and AWS helped turn a difficult business question into a working digital-twin platform</strong></p><p><strong>Series: </strong>Building TwinOS, Part 1 of 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KBglT6qVTNUr8iUOaKgtA.jpeg" /><figcaption><em>TwinOS gives small businesses a safe place to simulate decisions before acting.</em></figcaption></figure><p>Small and medium-sized businesses are often described as the backbone of the economy. Yet many of their most important decisions are still made with the thinnest possible safety net: a spreadsheet, a calculator, and the owner’s intuition.</p><p>Imagine a café owner named Sarah.</p><p>The price of coffee beans is about to rise. A key supplier has warned about delays. One employee wants a raise, while weekend queues suggest the business may need another pair of hands. Sarah is considering increasing menu prices, but she does not know how much demand might fall. She could hire another employee, but she does not know whether the extra capacity would generate enough revenue to cover payroll.</p><p>A large enterprise would model these questions before acting. It would use analysts, forecasting tools, internal data platforms, and simulation software.</p><p>Sarah has none of that.</p><p>She has to make a real decision with real consequences — and hope she guessed correctly.</p><p>That gap inspired <strong>TwinOS</strong>, an AI-assisted business simulation platform that gives small and medium-sized businesses a digital twin of their operations. TwinOS lets an owner model the business as it exists today, change a few assumptions, and explore what could happen before spending money or disrupting the team.</p><p>The simplest way to describe it is:</p><blockquote><strong>TwinOS is a flight simulator for business decisions.</strong></blockquote><p>This article explains where the idea came from, how I shaped the product with <strong>v0</strong>, and how the prototype evolved into a full-stack application deployed on <strong>Vercel</strong> and backed by <strong>AWS databases</strong>.</p><p><strong>Why reporting the past is not enough</strong></p><p>Most business software is retrospective.</p><p>Accounting tools explain what happened last month. Analytics dashboards show yesterday’s traffic. Point-of-sale systems show current sales. Inventory tools show what is available right now.</p><p>Those systems are valuable, but business owners also need to answer forward-looking questions:</p><ul><li>What happens if I raise prices by 8%?</li><li>Can I afford to hire two employees?</li><li>What happens to profit if marketing spend increases by 50%?</li><li>How badly would a two-week supplier delay affect inventory?</li><li>What is the least disruptive way to improve profit by 20%?</li></ul><p>A spreadsheet can answer some of these questions, but only when the assumptions are simple and the person using it understands every dependency. Once price, demand, labor, marketing, inventory, and fixed costs interact, the spreadsheet becomes fragile.</p><p>TwinOS was designed to make those relationships visible.</p><p>Instead of asking the user to become a financial modeller, it turns operational changes into understandable projections.</p><p><strong>The product idea: a living model of a business</strong></p><p>A digital twin is a virtual representation of a real-world system.</p><p>Digital twins are commonly associated with factories, aircraft, supply chains, and industrial equipment. Engineers use them to test changes without risking the physical system.</p><p>TwinOS applies that pattern to an SMB.</p><p>A TwinOS business twin contains a baseline model of:</p><ul><li>Revenue</li><li>Products and pricing</li><li>Product costs</li><li>Employees and payroll</li><li>Marketing spend</li><li>Fixed operating costs</li><li>Inventory assumptions</li><li>Historical performance</li><li>External integration data</li></ul><p>Once the baseline exists, the user can create scenarios such as:</p><ul><li>Increase prices by 10%</li><li>Add three employees</li><li>Reduce headcount by one</li><li>Increase marketing by $1,000</li><li>Model a supplier delay</li><li>Adjust inventory levels</li><li>Combine several changes into one scenario</li></ul><p>The platform then compares the scenario against the baseline over a selected time horizon, such as 30, 90, or 365 days.</p><p>The user sees projected effects on:</p><ul><li>Gross revenue</li><li>Net profit</li><li>Employee capacity</li><li>Inventory or stockout risk</li><li>Costs</li><li>Recommended actions</li></ul><p>This changes the conversation from:</p><blockquote>What do you think will happen?</blockquote><p>to:</p><blockquote>Here are the assumptions, here is the model, and here is the projected trade-off.</blockquote><p><strong>Starting with v0: prototyping the experience before committing to the code</strong></p><p>The project began with product design, not database design.</p><p>I knew the application would need several complex interfaces:</p><ul><li>A business overview dashboard</li><li>A scenario simulator</li><li>A scenario comparison screen</li><li>A Counterfactual Explorer</li><li>Integration settings</li><li>Workspace administration</li><li>Financial charts and projections</li></ul><p>Building all of these from scratch before validating the flow would have been slow. I used <strong>v0 by Vercel </strong>to rapidly prototype the experience.</p><p>I described the interface in plain language, including the product goal, the information hierarchy, and the interaction pattern. For example, a prompt could describe:</p><ul><li>A B2B analytics dashboard</li><li>A left navigation rail</li><li>KPI cards for revenue, profit, headcount, and stockout risk</li><li>Recharts visualizations</li><li>A large action panel for recommendations</li><li>A minimal Vercel-inspired visual style</li><li>Responsive behavior for desktop and tablet</li></ul><p>v0 helped me move from an abstract idea to something I could inspect, click through, and challenge.</p><p>That mattered because the hardest part of TwinOS was not drawing cards on a screen. It was deciding what the user needed to see first.</p><p>For example:</p><ul><li>Should the scenario controls appear beside the forecast or above it?</li><li>Should the result screen lead with profit or revenue?</li><li>How should baseline and optimized values be distinguished?</li><li>How can a recommendation feel actionable rather than merely analytical?</li><li>How do we present uncertainty without overwhelming a non-technical owner?</li></ul><p>v0 gave me a fast feedback loop. I could generate a direction, reject weak ideas, keep the strongest patterns, and then rebuild the final experience in the production application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVcYpTNPupRNeR4K3Bz2QA.jpeg" /><figcaption><em>v0 accelerated the interface exploration, while the production experience was rebuilt and connected to real application state.</em></figcaption></figure><p>The final frontend was implemented with:</p><ul><li><strong>Next.js App Router</strong></li><li><strong>React</strong></li><li><strong>TypeScript</strong></li><li><strong>Tailwind CSS</strong></li><li><strong>Recharts</strong></li><li><strong>Clerk</strong> for authentication</li><li><strong>Vercel</strong> for deployment</li></ul><p>The important distinction is that v0 accelerated the design and prototyping process; it did not remove the need for engineering. I still had to connect real state, validate forms, build APIs, integrate authentication, handle loading and failure states, and make the frontend work against production data.</p><p><strong>The four core product systems</strong></p><p>TwinOS is built around four connected systems.</p><p><strong>1. Digital Twin Builder</strong></p><p>The Digital Twin Builder creates the baseline representation of the business.</p><p>A user can enter information manually or synchronize data from external systems. The current integration architecture supports:</p><p>- <strong>QuickBooks</strong> for financial data</p><p>- <strong>Shopify</strong> for products and commerce data</p><p>- <strong>Square POS</strong> for labor or point-of-sale data</p><p>The platform also includes sandbox and mock modes. That allows the product to be tested even when live developer credentials are unavailable, and it makes the hackathon demonstration repeatable.</p><p>This was important. A good demo should not collapse because an external API is rate-limited or an OAuth credential expires five minutes before recording.</p><p><strong>2. Scenario Engine</strong></p><p>The Scenario Engine lets the owner describe a hypothetical future.</p><p>A scenario is a structured set of changes applied to the baseline business state.</p><p>For example:</p><pre>Price adjustment: +8%<br>Marketing budget: +$500/month<br>Headcount: +1 employee<br>Supplier delay: 0 days<br>Forecast horizon: 90 day</pre><p>TwinOS then calculates the new projected state and stores both the inputs and outputs so the result can be compared later.</p><p><strong>3. Forecasting Engine</strong></p><p>The forecasting engine uses deterministic formulas to estimate changes in demand, revenue, costs, capacity, and inventory pressure.</p><p>The goal is not to pretend that a model can predict the future perfectly. The goal is to help the owner understand the direction and magnitude of likely trade-offs.</p><p>A model can show, for example, that:</p><ul><li>Revenue may rise after a price increase</li><li>Demand may fall because of elasticity</li><li>Profit may still improve because the margin increase outweighs lost volume</li><li>A new employee may increase capacity but lower short-term profit</li><li>A supplier delay may create stockout risk even when demand is strong</li></ul><p>These relationships are more useful than a single unexplained number.</p><p><strong>4. Counterfactual Explorer</strong></p><p>The Counterfactual Explorer reverses the normal simulation workflow.</p><p>A traditional simulator asks:</p><blockquote>What happens if I change these inputs?</blockquote><p>The Counterfactual Explorer asks:</p><blockquote>What inputs should change to reach this target?</blockquote><p>The user can select a goal such as:</p><ul><li>Increase profit by 20%</li><li>Increase revenue by 15%</li><li>Reduce stockout risk</li><li>Improve capacity without increasing payroll beyond a limit</li></ul><p>TwinOS searches possible combinations and returns a recommended action plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBMgThSr0K37gjUkxs4J5Q.jpeg" /><figcaption><em>Users define a financial goal and TwinOS searches for a low-disruption path toward it</em></figcaption></figure><p>This is where TwinOS moves beyond dashboards and becomes a decision-support system.</p><p><strong>Why the platform combines formulas with AI explanations</strong></p><p>One of the clearest lessons from building TwinOS was that financial recommendations cannot feel like magic.</p><p>A business owner may enjoy an AI-generated summary, but they should not have to trust a black box with payroll, pricing, or inventory.</p><p>TwinOS separates two responsibilities:</p><p>1. <strong>The deterministic simulation engine calculates the numbers.</strong></p><p>2. <strong>The AI layer explains the result in plain language.</strong></p><p>The AI does not invent the forecast. It receives structured outputs from the simulation and turns them into an understandable explanation.</p><p>For example, instead of presenting only:</p><pre>Projected net profit: +18.4%</pre><p>TwinOS can explain:</p><blockquote>Profit improves because the price adjustment increases gross margin while the projected demand decline remains small. Headcount is unchanged, so payroll remains stable. Marketing spend increases modestly and is offset by the additional revenue.</blockquote><p>This approach makes the product more trustworthy and more useful.</p><p>It also creates a clean technical boundary: deterministic calculations remain testable, while the language layer remains flexible.</p><p><strong>Designing for real-world messiness</strong></p><p>A simulation product can look impressive while quietly making unrealistic recommendations.</p><p>Suppose the mathematically optimal solution is to remove half the staff and double prices. That may maximize a formula, but it is not useful advice.</p><p>TwinOS therefore treats operational disruption as a cost.</p><p>Staffing changes are expensive because they affect people, service quality, training, morale, and legal obligations. Pricing changes may be easier, but they can still affect demand and brand perception. Marketing adjustments are often more reversible.</p><p>The optimization system considers those differences so it can prefer a slightly less profitable but much more practical plan.</p><p>This is a key product principle:</p><blockquote><strong>The best recommendation is not merely the one with the highest number. It is the one a real business can reasonably execute.</strong></blockquote><p><strong>What I learned while building TwinOS</strong></p><p><strong><em>Product clarity matters more than feature count</em></strong></p><p>It was tempting to add every possible feature: more charts, more integrations, more metrics, more configuration.</p><p>The stronger product emerged when the experience focused on one promise:</p><blockquote>Help an SMB owner test a decision before making it.</blockquote><p>Every major screen now supports that promise.</p><p><strong>Transparent models create trust</strong></p><p>Users do not need every equation on the main dashboard, but they do need understandable reasoning.</p><p>Explaining the causal chain behind a result makes the tool feel less like a prediction machine and more like a knowledgeable assistant.</p><p><strong>v0 is most valuable as a thinking partner</strong></p><p>The fastest part of the build was generating UI. The most valuable part was using those prototypes to discover what the product should be.</p><p>v0 shortened the distance between an idea and a testable interface.</p><p><strong>Cloud infrastructure can become part of the product story</strong></p><p>AWS Aurora and DynamoDB were not included merely to satisfy a hackathon requirement. They serve different workloads inside TwinOS:</p><p>- Aurora stores the relational business twin and scenario history.</p><p>- DynamoDB handles fast cache and optimization telemetry workloads.</p><p>That architecture is explored in Part 2.</p><p><strong>What is next for TwinOS</strong></p><p>The current optimization engine uses hill climbing to search for better operating states. Future versions will expand this with:</p><ul><li>Genetic algorithms</li><li>Multi-objective optimization</li><li>Industry-specific simulation templates</li><li>Real-time multi-user collaboration</li><li>Confidence ranges and sensitivity analysis</li><li>Continuous monitoring of actual versus predicted outcomes</li><li>Automated model recalibration</li><li>Additional accounting, commerce, and POS integrations</li></ul><p>The long-term vision is not to replace business owners.</p><p>It is to give them a safe place to reason about the future.</p><p>Every business decision creates a branch in the road. TwinOS makes those branches visible before the owner has to walk down one.</p><p><strong>Continue the series</strong></p><p>- <strong>Part 2:</strong> Building TwinOS with AWS Aurora, DynamoDB, Prisma, and Vercel</p><p>- <strong>Part 3:</strong> Engineering the Counterfactual Explorer and its optimization model</p><p><em>*I created this article for the purpose of entering the Hack the Zero Stack (H0) Hackathon. TwinOS was built using Vercel, v0, AWS Aurora PostgreSQL, Amazon DynamoDB, Next.js, Prisma, and Clerk. #H0Hackathon*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bfb52590104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Blockchain Networks Stay Safe: A Simple Guide to Proof of Stake vs Proof of Work]]></title>
            <link>https://maylord.medium.com/how-blockchain-networks-stay-safe-a-simple-guide-to-proof-of-stake-vs-proof-of-work-fd91ac56270a?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd91ac56270a</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[consensus-mechanism]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Wed, 30 Jul 2025 16:32:04 GMT</pubDate>
            <atom:updated>2025-07-30T16:32:04.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ycS8QoBJjb0xcLk5QEnuvg.png" /></figure><h3>What Are Consensus Mechanisms?</h3><p>A consensus mechanism is a protocol used in blockchain networks to achieve agreement among distributed nodes about the state of the ledger, ensuring all participants have the same version of the blockchain without requiring a central authority</p><p>Think of a blockchain like a shared notebook that everyone in a group needs to agree on. But there’s no teacher or boss to decide what gets written in it. Consensus mechanisms are the rules that help everyone agree on what should be written in this shared notebook without fighting about it.</p><h3>Types of Consensus Mechanisms</h3><p>There are several different consensus mechanisms that blockchain networks can use. Each has its own rules for who gets to make decisions and how those decisions are validated. These include</p><ul><li><strong>Proof of Work (PoW)</strong></li><li><strong>Proof of Stake (PoS)</strong></li><li><strong>Delegated Proof of Stake (DPoS)</strong></li><li><strong>Proof of Authority (PoA)</strong></li><li><strong>Practical Byzantine Fault Tolerance (pBFT)</strong></li></ul><p>These mechanisms differ in their assumptions about network conditions, threat models, and trade-offs between decentralization, security, and scalability known as the blockchain trilemma. However in this article, we will be talking extensively about Proof of Stake and how it compares to Proof of Work.</p><h3>What is Proof of Stake ?</h3><p>Proof of Stake is a consensus algorithm where validators are chosen to create new blocks based on their economic stake in the network. The selection probability is typically proportional to the amount of cryptocurrency they have locked up as collateral. Imagine you’re in a club where people take turns being the leader for the day. In Proof of Stake, the person who gets to be leader called a <strong>validator</strong> is chosen based on how much money they’ve put into the club’s piggy bank.</p><p>Here’s how it works:</p><ul><li>People put their cryptocurrency into a special account, this is called staking.</li><li>The computer randomly picks someone to be the next leader but people with more money staked have a better chance of being picked.</li><li>The leader gets to add the next page to the shared notebook and earns some reward money.</li><li>If the leader cheats or makes mistakes, they lose some of their staked money as punishment.</li></ul><p><strong>Key Terms:</strong></p><ul><li><strong>Validator</strong>: A network participant who validates transactions and creates new blocks.</li><li><strong>Staking</strong>: The process of locking up cryptocurrency as collateral to participate in consensus.</li><li><strong>Slashing</strong>: The penalty mechanism that destroys part of a validator’s stake for malicious behavior.</li></ul><h3>The Good Things About Proof of Stake</h3><h4>- It’s Like Having Skin in the Game</h4><p>When you stake your money, you really care about the network staying safe because if it gets attacked or breaks, your money becomes worthless. It’s like owning shares in a company and thus you want the company to do well.</p><h4>- It Uses Less Electricity</h4><p>Unlike Bitcoin mining that uses tons of electricity, Proof of Stake doesn’t need powerful computers running 24/7. This makes it much more environmentally friendly.</p><h4>- Faster Decisions</h4><p>In Proof of Stake, once enough validators agree on something, it’s final — like getting enough signatures on a petition. You don’t have to wait as long to be sure your transaction went through.</p><h3>The Problems with Proof of Stake</h3><h4>- The “Nothing to Lose” Problem</h4><p>This is called the “Nothing at Stake” problem because validators can theoretically vote on multiple competing blockchain forks simultaneously without additional cost, potentially leading to consensus failures. Since it doesn’t cost extra computer power, a dishonest validator might try to validate two different versions of the notebook at the same time. It’s like voting for two different people in the same election hoping one of them wins.</p><h4>- The Rich Get Richer</h4><p>People with more money get picked more often to be validators and earn more rewards. Over time, this could make the rich people even richer and give them too much control.</p><h4>- History Rewriting Attacks</h4><p>These are called “Long-Range Attacks” where an attacker with historical stake attempts to create an alternative blockchain history from a point in the past when they controlled significant stake.</p><h3>How Does It Stop Cheating?</h3><h4>- Preventing Double-Spending</h4><p>Double-spending prevention relies on cryptographic signatures, economic penalties for equivocation (signing conflicting transactions), and finality mechanisms that make transaction reversal computationally or economically infeasible, Double-spending is like trying to spend the same $20 bill twice. Proof of stake stops this by:</p><ul><li>Making validators lose their staked money if they try to approve fake transactions.</li><li>Making it really expensive to control enough of the network to cheat.</li><li>Finalizing transactions quickly so they can’t be changed later.</li></ul><h4>- Stopping 51% Attacks</h4><p>A 51% attack is when someone controls more than half the network and can change the rules. In Proof of Stake:</p><ul><li>An attacker would need to own more than half of all the staked cryptocurrency.</li><li>This would cost billions of dollars for major networks like Ethereum.</li><li>If they attack the network, the value of their own cryptocurrency would crash, making them lose money.</li><li>Their staked money can be taken away as punishment.</li></ul><p>The economic security comes from the fact that successful attacks devalue the attacker’s own holdings.</p><h3>Comparing Proof of Stake to Proof of Work (Bitcoin’s System)</h3><h3>Proof of Work</h3><ul><li><strong>How it works</strong>: Computers race to solve math puzzles, winner gets to add the next block.</li><li><strong>Security</strong>: Protected by the massive amount of electricity and computer power needed to attack it.</li><li><strong>Problems</strong>: Uses lots of electricity, can be slow, mining equipment gets centralized.</li></ul><p>PoW uses cryptographic hash functions (like SHA-256) to create computational puzzles. Miners must find a nonce (number used once) that, when combined with block data, produces a hash with a specific number of leading zeros. The difficulty adjusts automatically to maintain consistent block times.</p><h3>Proof of Stake</h3><ul><li><strong>How it works</strong>: People stake their money, get randomly selected to validate transactions</li><li><strong>Security</strong>: Protected by economic penalties and the cost of buying enough cryptocurrency to attack</li><li><strong>Problems</strong>: Rich people have more influence, some technical challenges to solve</li></ul><p>PoS uses various randomization algorithms like RANDAO or Verifiable Random Functions(VRF) for validator selection. Security relies on game theory and economic incentives rather than computational work. Many implementations use BFT consensus protocols for immediate finality.</p><h3>Which is More Secure?</h3><p>Both systems are secure but in different ways:</p><p><strong>Proof of Work</strong> is like a fortress protected by a huge wall that requires massive resources to break through. But maintaining that wall uses a lot of energy.</p><p><strong>Proof of Stake</strong> is like a fortress where the guards are also the owners — they protect it carefully because if it falls, they lose their investment. It uses less energy but requires careful rules to prevent the owners from becoming too powerful.</p><h3>Real-World Examples</h3><ul><li><strong>Bitcoin</strong> uses Proof of Work</li><li><strong>Ethereum</strong> switched from Proof of Work to Proof of Stake in 2022</li><li><strong>Cardano, Solana, and Polkadot</strong> use variations of Proof of Stake</li></ul><h3>The Bottom Line</h3><p>Proof of Stake is like having a democratic system where your voting power depends on how much you’ve invested in the community. It’s more energy-efficient than Proof of Work and can be just as secure when designed properly. However, it requires careful balance to prevent wealthy participants from having too much control.</p><p>Both systems have proven they can protect billions of dollars worth of cryptocurrency, but they do it in very different ways. The choice between them often comes down to priorities: energy efficiency and speed in Proof of Stake versus battle-tested security and decentralization in Proof of Work.</p><p>See you next time, Ciao.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd91ac56270a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React Hooks: A Guide for Newbies]]></title>
            <link>https://maylord.medium.com/understanding-react-hooks-a-guide-for-newbies-80fa9221a3ad?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/80fa9221a3ad</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web2-vs-web3]]></category>
            <category><![CDATA[hooks-in-react]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 16:08:30 GMT</pubDate>
            <atom:updated>2025-03-07T16:08:30.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrH6P_BJ10DdckmGWOOA_g.jpeg" /></figure><p>React hooks were introduced to make it easier to manage state, side effects, and other features in functional components without the need for class components, this shift helps developers write cleaner, more modular code and share logic across different parts of an app easily. This guide focuses on the six most essential hooks: useState, useEffect, useContext, useMemo, useRef, and useCallback. Here’s a summary of how React hooks help simplify the development process:</p><ul><li><strong>Avoid Complexity</strong>: No need for class components anymore, which come with more boilerplate code.</li><li><strong>Reusable Logic</strong>: Custom hooks allow you to extract logic and reuse it across components, helping to avoid redundancy.</li><li><strong>Cleaner Components</strong>: Instead of having large class components, functional components with hooks are usually more concise and focused.</li><li><strong>Rules of Hooks</strong>: Hooks must be used at the top level of components and in React function components only. These rules ensure that React can correctly manage hook state across renders.</li></ul><h3>1. useState — Managing State</h3><p>The useState hook adds state to functional components. It initializes state with a given value, and it returns an array where the first element is the current state value and the second is a function to update it. React automatically re-renders the component when the state is updated, reflecting changes in the UI. It is used when you need to keep track of any piece of data that can change over time. For Example,</p><pre>import { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, useState(0) creates a state variable called count with an initial value of 0 and returns a setter function setCount. When the button is clicked, setCount(count + 1) updates the count value and triggers a re-render of the component. This is the fundamental mechanism for adding reactive state to functional components. Unlike class components where all state lives in a single object, with hooks you can split state into multiple variables for better organization.</p><h3>2. useEffect — Handling Side Effects</h3><p>The useEffect allows you to run side effects in your components. Side effects include things like data fetching, DOM manipulation, or subscribing to external services. It takes two arguments: a function to run, and an optional dependency array. If the array is empty, the effect will run only once. For Example,</p><pre>import { useState, useEffect } from &quot;react&quot;;<br><br>function FetchData() {<br>  const [data, setData] = useState([]);<br>  useEffect(() =&gt; {<br>    fetch(&quot;https://jsonplaceholder.typicode.com/posts&quot;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; setData(data));<br>  }, []); // Empty array means run once on mount<br>  return (<br>    &lt;ul&gt;<br>      {data.slice(0, 5).map((item) =&gt; (<br>        &lt;li key={item.id}&gt;{item.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>This code demonstrates how useEffect fetches data when the component mounts. The empty dependency array ensures the effect runs only once after the initial render. If you omit the dependency array, the effect runs after every render. If you include values in the array, the effect runs whenever those values change. The function can also return a cleanup function that runs before the component unmounts or before the effect runs again.</p><h3>3. useContext — Managing Global State</h3><p>The useContext hook shares state across components without prop drilling. It is useful for values that need to be accessible globally, like themes, localization, and user authentication information. For Example,</p><pre>import { createContext, useContext, useState } from &quot;react&quot;;<br><br>const ThemeContext = createContext();<br>function ThemeProvider({ children }) {<br>  const [theme, setTheme] = useState(&quot;light&quot;);<br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}<br>function ThemedComponent() {<br>  const { theme, setTheme } = useContext(ThemeContext);<br>  return (<br>    &lt;div style={{ background: theme === &quot;light&quot; ? &quot;#fff&quot; : &quot;#333&quot; }}&gt;<br>      &lt;button onClick={() =&gt; setTheme(theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;)}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, useContext provides a way to consume context values without nesting consumer components. First, we create a context with createContext(), then provide values to it with ThemeContext.Provider. Any component within the provider tree can access those values using useContext(ThemeContext). This effectively creates a global state that components can read from and write to without passing props through intermediate components.</p><h3>4. useMemo — Optimizing Performance</h3><p>The useMemo hook remembers expensive calculations to prevent unnecessary recomputation of values during re-renders thereby improving performance. It is also useful when filtering data. For Example,</p><pre>import { useState, useMemo } from &quot;react&quot;;<br><br>function ExpensiveComponent({ number }) {<br>  const squaredNumber = useMemo(() =&gt; {<br>    console.log(&quot;Computing...&quot;);<br>    return number * number;<br>  }, [number]);<br>  return &lt;p&gt;Squared Number: {squaredNumber}&lt;/p&gt;;<br>}</pre><p>Here, useMemo prevents the squaring calculation from running on every render. The memoized value squaredNumber only updates when the number prop changes. This is crucial for performance optimization when dealing with expensive calculations like filtering large arrays, complex mathematical operations, or generating derived data. The function inside useMemo runs during rendering, and the result is stored until the dependencies change. Without memoization, the calculation would run on every render, even if number hasn&#39;t changed.</p><h3>5. useRef — Accessing DOM &amp; Persisting Values</h3><p>The useRef hook accesses DOM elements and stores mutable values without causing re-renders. Unlike state, updating a ref doesn’t trigger a re-render of the component. This makes it great for accessing DOM elements (like focusing an input) or persisting values that don’t need to cause a re-render. For Example,</p><pre>import { useRef } from &quot;react&quot;;<br><br>function FocusInput() {<br>  const inputRef = useRef(null);<br>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} type=&quot;text&quot; /&gt;<br>      &lt;button onClick={() =&gt; inputRef.current.focus()}&gt;Focus Input&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, useRef creates a reference to the input element, allowing direct access to DOM methods like focus(). The ref object has a current property that persists between renders but doesn&#39;t trigger re-renders when changed. Beyond DOM access, useRef is useful for storing any mutable value that needs to persist across renders without affecting the UI, such as previous state values, interval IDs, or instance variables. Think of refs as instance variables in class components that don&#39;t cause re-rendering when updated.</p><h3>6. useCallback — Memoizing Functions</h3><p>The useCallback hook memoizes functions so that they don’t get recreated on every render. This is especially helpful when passing functions as props to child components, as it prevents unnecessary re-renders of those child components, particularly when the child is optimized with React.memo or when the function is a dependency of another hook like useEffect. For Example,</p><pre>import { useState, useCallback } from &quot;react&quot;;<br><br>function Button({ handleClick }) {<br>  return &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;;<br>}<br>function App() {<br>  const [count, setCount] = useState(0);<br>  const increment = useCallback(() =&gt; {<br>    setCount((prev) =&gt; prev + 1);<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;Button handleClick={increment} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this code, useCallback ensures the increment function maintains the same reference between renders. Without useCallback, a new function would be created on each render, potentially causing child components to re-render unnecessarily. The empty dependency array means the function never changes; if you include dependencies, the function will be recreated when those values change.</p><h3>Other React Hooks</h3><p>While we’ve focused on these six hooks, React provides several others including useReducer (for complex state logic), useLayoutEffect (for synchronous effects), useImperativeHandle (for customizing refs), useDebugValue (for debugging), and more recent additions like useId, useDeferredValue, and useTransition.</p><h3>Conclusion</h3><p>These six React hooks namely useState, useEffect, useContext, useMemo, useRef, and useCallback form the foundation of modern React development. They enable functional components to handle everything class components could do and more, with cleaner, more reusable code. Understanding when and how to use each hook will help you write more efficient React applications with better component architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80fa9221a3ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ERC-721 Tokens: A Fun Dive into How NFTs are Built on Ethereum]]></title>
            <link>https://blog.blockmagnates.com/understanding-erc-721-tokens-a-fun-dive-into-how-nfts-are-built-on-ethereum-e224e52d3465?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e224e52d3465</guid>
            <category><![CDATA[onchain]]></category>
            <category><![CDATA[erc721]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[nft]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 14:30:08 GMT</pubDate>
            <atom:updated>2025-03-03T12:50:26.176Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, we will talk about NFTs, their use cases, how ERC-721 helps us create NFTs and then break down a smart contract called NFTOnChain line by line to understand its structure, functionality, and purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-xU18bEyukCcLNNWy1kaQ.jpeg" /></figure><h3>What Are NFTs and Why the Buzz?</h3><p>Ever wondered how those digital apes sold for millions? Or why people are spending real money on virtual art that you can’t even hang on your wall?</p><p>Well, NFTs (Non-Fungible Tokens) are unique digital assets stored on a blockchain. NFTs have distinct properties that make each one unique. This uniqueness makes them ideal for representing digital collectibles, artwork, and more. Think of NFTs as digital collectible cards but instead of finding them in chocolate treats, they live on the blockchain and just like how that rare pokémon card might be the missing piece in a collectors’ albums, digital scarcity creates value in fascinating ways.</p><h3>Use Cases of NFTs</h3><p>NFTs have numerous applications across various industries, including:</p><ul><li><strong>Digital Art &amp; Collectibles</strong>: Artists can tokenize their artwork and sell them as NFTs.</li><li><strong>Gaming</strong>: Players can own, trade, and sell in-game assets as NFTs.</li><li><strong>Real Estate</strong>: NFTs can represent ownership of virtual or real-world properties.</li><li><strong>Music &amp; Entertainment</strong>: Musicians can tokenize their songs and sell them as NFTs.</li><li><strong>Identity &amp; Certification</strong>: NFTs can store digital certificates, diplomas, or identity proofs.</li></ul><p>Several prominent decentralized applications (dApps) are built around NFTs, including OpenSea, the largest NFT marketplace for buying, selling, and trading NFTs; Rarible, a decentralized NFT marketplace that allows users to mint and sell NFTs; Foundation, a creator-focused platform for digital artists; Decentraland, a virtual world where users can buy, sell, and trade virtual land as NFTs; and Axie Infinity, a play-to-earn game where players own and trade NFT-based creatures.</p><h3>ERC-721: The Secret Sauce Behind NFTs</h3><p>Before I bore you yet again with yet another crypto acronym, let’s break this down: ERC-721 is basically the recipe that tells Ethereum how to create unique digital items. Unlike cryptocurrencies where each coin is identical (one Bitcoin = another Bitcoin), I have an article that explains ERC-20 tokens <a href="https://maylord.medium.com/understanding-erc-20-tokens-the-backbone-of-ethereums-token-economy-c21de077cf2f">here</a>, ERC-721 lets developers create one-of-a-kind digital assets.</p><p>ERC-721 is the Ethereum standard for creating NFTs. Introduced as an <a href="https://eips.ethereum.org/EIPS/eip-721">Ethereum Improvement Proposal (EIP-721)</a>, it defines the functions and structure that NFT contracts must follow. Key features of ERC-721 include:</p><ul><li><strong>Uniqueness</strong>: Each token has a unique tokenId.</li><li><strong>Ownership</strong>: Each token is owned by an Ethereum address.</li><li><strong>Transferability</strong>: Owners can transfer tokens using the transferFrom function.</li><li><strong>Metadata</strong>: Each token can store metadata, including images, descriptions, and names.</li></ul><h3>Looking Under the Hood: The NFTOnChain Contract</h3><p>Let’s peek behind the curtain and see what makes this NFT contract tick. Our <em>NFTOnChain</em> example is like a digital factory that produces unique collectibles. Don’t worry even if you don’t write <em>solidity</em> which is the coding language used here I will translate the tech-speak.</p><h3>The Building Blocks</h3><pre>// SPDX-License-Identifier: UNLICENSED<br>pragma solidity ^0.8.28;</pre><p>We start with the License identifier which declares that it is <strong>unlicensed</strong> (not bound by any specific license) and then specifies the Solidity version ^0.8.28 .</p><pre>import &quot;@openzeppelin/contracts/token/ERC721/ERC721.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/Base64.sol&quot;;<br>import &quot;@openzeppelin/contracts/utils/Strings.sol&quot;;<br>import &quot;@openzeppelin/contracts/access/Ownable.sol&quot;;</pre><p>Think of these lines as ingredients for our recipe. We’re grabbing pre-made components(libraries) from OpenZeppelin that thousands of developers use so they don’t accidentally create something unstable.</p><p>These imports bring in OpenZeppelin’s:</p><ul><li><strong>ERC721</strong>: Standard implementation for NFTs.</li><li><strong>Base64</strong>: Helps encode metadata as Base64.</li><li><strong>Strings</strong>: Utility functions for manipulating numbers as strings.</li><li><strong>Ownable</strong>: Provides ownership functionality for contract control.</li></ul><h3>The Contract’s DNA</h3><pre>contract NFTOnChain is ERC721, Ownable {<br>    using Strings for uint256;<br>    <br>    uint256 private _tokenIdCounter;<br>    uint256 public immutable MAX_SUPPLY;</pre><p>This part defines our NFT’s personality. It’s like filling out its identity card:</p><ul><li>NFTOnChain inherits from ERC721 (for NFT functionality) and Ownable (to restrict certain actions to the contract owner).</li><li>This enables uint256 values to be converted to strings easily using OpenZeppelin’s Strings library.</li><li>We’re tracking how many NFTs exist with _tokenIdCounter .</li><li>Setting a limit with MAX_SUPPLY .</li></ul><h3>Preventing Disasters with Custom Errors</h3><pre>error TokenNotFound();<br>error MaxSupplyReached();</pre><p>These are like putting guardrails on a mountain road. If someone tries to view a token that doesn’t exist or mint beyond our maximum supply, they’ll get a friendly but firm error message instead of crashing. Plus, these <a href="https://coinsbench.com/day-24-optimizing-gas-in-solidity-with-custom-errors-and-reverts-0835a0cd1434">custom errors save gas fees</a>, think efficiency on the blockchain.</p><h3>The Creation Factory</h3><pre>constructor(<br>    string memory name_,<br>    string memory symbol_,<br>    uint256 maxSupply_<br>) ERC721(name_, symbol_) Ownable(msg.sender) {<br>    MAX_SUPPLY = maxSupply_;<br>}</pre><p>This constructor is like setting up your own collectible shop on opening day. You decide on your brand name, symbol, and how many limited edition items you’ll ever create and then assign ownership to the contract deployer using OpenZeppelin’s Ownable library . After this moment, some settings (like MAX_SUPPLY) are locked in forever, there are no take-backs on the blockchain because of its immutability.</p><h3>Minting: The Magic Moment</h3><pre>function mint() public {<br>    if (_tokenIdCounter &gt;= MAX_SUPPLY) revert MaxSupplyReached();<br>    _tokenIdCounter += 1;<br>    _safeMint(msg.sender, _tokenIdCounter);<br>}</pre><p>This is where new NFTs come to life, It’s like pressing the “CREATE” button on your digital collectible machine. The function checks if we’ve hit our maximum supply (sorry, no more limited editions for you), then it increments our _tokenIdCounter, and calls _safeMint() to deliver a fresh NFT to whoever called the function.</p><h3>The Soul of the NFT: Metadata</h3><pre>function tokenURI(uint256 tokenId) public view override returns (string memory) {<br>    if(ownerOf(tokenId) == address(0)) revert TokenNotFound();<br><br>    string memory name = string(abi.encodePacked(name(), &quot; #&quot;, tokenId.toString()));<br>    string memory description = &quot;This is an on-chain NFT&quot;;<br>    string memory image = generateBase64Image();<br><br>    string memory json = string(<br>        abi.encodePacked(<br>            &#39;{&quot;name&quot;:&quot;&#39;, name, &#39;&quot;,&#39;,<br>            &#39;&quot;description&quot;:&quot;&#39;, description, &#39;&quot;,&#39;,<br>            &#39;&quot;image&quot;:&quot;&#39;, image, &#39;&quot;}&#39;<br>        )<br>    );<br>    return string(abi.encodePacked(&quot;data:application/json;base64,&quot;, Base64.encode(bytes(json))));<br>}</pre><p>This function is like the identity card of your NFT, The function first checks if the token exist then it creates a complete profile for your NFT including:</p><ul><li>Its official name (like “HarryPotter #42”)</li><li>A description</li><li>The actual image (we’ll see how that’s created next)</li></ul><p>All this gets packaged up as a JSON file and encoded in Base64 as a string to return an on-chain tokenURIso it can live entirely on the blockchain with No servers required.</p><h3>Creating Digital Art On-Chain</h3><pre>function generateBase64Image() internal pure returns (string memory) {<br>    string memory svg = &#39;&lt;svg width=&quot;200&quot; height=&quot;60&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;&lt;style&gt;&#39;<br>                        &#39;text { paint-order: stroke; stroke: white; stroke-width: 2px; fill: black; text-anchor: middle;}&lt;/style&gt;&#39;<br>                        &#39;&lt;defs&gt;&lt;linearGradient id=&quot;gradient&quot; x1=&quot;0%&quot; x2=&quot;100%&quot; y1=&quot;0%&quot; y2=&quot;0%&quot;&gt;&#39;<br>                        &#39;&lt;stop offset=&quot;0%&quot; stop-color=&quot;#00ff6e&quot;/&gt;&#39;<br>                        &#39;&lt;stop offset=&quot;100%&quot; stop-color=&quot;#f4774e&quot;/&gt;&lt;/linearGradient&gt;&lt;/defs&gt;&#39;<br>                        &#39;&lt;rect width=&quot;100%&quot; height=&quot;100%&quot; rx=&quot;10&quot; ry=&quot;10&quot; fill=&quot;url(#gradient)&quot;/&gt;&#39;<br>                        &#39;&lt;text x=&quot;50%&quot; y=&quot;50%&quot; dy=&quot;0.35em&quot; font-size=&quot;24px&quot;&gt;MayNFT&lt;/text&gt;&#39;<br>                        &#39;&lt;/svg&gt;&#39;;<br>    return string(abi.encodePacked(&quot;data:image/svg+xml;base64,&quot;, Base64.encode(bytes(svg))));<br>}</pre><p>This is where the actual digital art magic happens, Instead of pointing to an image on some server that could disappear tomorrow, we’re creating vector art directly in the contract using SVG (Scalable Vector Graphics).</p><p>It’s like embedding a tiny art studio inside the NFT itself. This particular example creates a sleek rectangle with a green-to-orange gradient and the text “MayNFT” in the middle. Not exactly a masterpiece, but hey it’s immortalized on the <a href="https://testnets.opensea.io/assets/sepolia/0xaec66e26188fc90dc1fb67016b9a42a4dfc6c987/1/">blockchain</a> forever.</p><h3>Why This Matters: True Digital Ownership</h3><p>This NFT is completely self-contained on the Ethereum blockchain. Unlike many NFTs that store their images on IPFS or regular web servers (which can disappear), this one is truly decentralized.</p><h3>Try It Yourself!</h3><p>Want to mint your own on-chain NFT? Here’s how:</p><ol><li>Head over to my <a href="https://github.com/7maylord/NFTOnChain">GitHub</a> and clone the repo.</li><li>Install the dependencies and run the deploy script.</li><li>Check the README.md for detailed steps.</li></ol><p>We’re deploying the NFT to a testnet, so if successful:</p><ul><li>Go to <a href="http://testnets.opensea.io/">testnets.opensea.io</a></li><li>Connect your wallet.</li><li>Navigate to your profile to view your freshly minted NFT!</li></ul><p>No need to be a wizard , just follow the steps and bring your NFT to life!</p><h3>Conclusion: The Future is Tokenized</h3><p>Whether you think NFTs are just a passing fad or the future of ownership, the technology behind them is fascinating. By understanding ERC721 and how these contracts work, you’ve taken your first step into a larger digital world of collectibles and ownership.</p><p>🔗 <strong>Follow me on Medium for more blockchain insights.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e224e52d3465" width="1" height="1" alt=""><hr><p><a href="https://blog.blockmagnates.com/understanding-erc-721-tokens-a-fun-dive-into-how-nfts-are-built-on-ethereum-e224e52d3465">Understanding ERC-721 Tokens: A Fun Dive into How NFTs are Built on Ethereum</a> was originally published in <a href="https://blog.blockmagnates.com/">Block Magnates</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ERC-20 Tokens: The Backbone of Ethereum’s Token Economy]]></title>
            <link>https://maylord.medium.com/understanding-erc-20-tokens-the-backbone-of-ethereums-token-economy-c21de077cf2f?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c21de077cf2f</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[erc20-token]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[tokenomics]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 13:03:18 GMT</pubDate>
            <atom:updated>2025-02-26T13:03:18.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Ever wondered how stablecoins like USDT or DeFi platforms like Uniswap operate seamlessly on Ethereum? The answer lies in ERC-20 tokens — the backbone of the Ethereum token ecosystem. These tokens provide a standardized framework for creating and managing digital assets on Ethereum, enabling interoperability across wallets, exchanges, and decentralized applications (dApps).</p><p>This article will walk you through what ERC-20 tokens are, their use cases, a simple implementation, and how they power major DeFi and blockchain applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Sc6GigGdBj82aWqUw_4MA.jpeg" /></figure><h3>What is an ERC-20 Token?</h3><p>An ERC-20 token is a fungible token standard on the Ethereum blockchain. “Fungible” means that each token is identical to another, making ERC-20 tokens ideal for digital currencies, stablecoins, and utility tokens. It defines a common set of rules that all ERC-20 tokens must follow, enabling seamless interaction between tokens and decentralized applications (dApps). Examples include USDT, DAI, LINK, AAVE, SUSHI, YFI, CAKE.</p><h3>ERC20 Functions</h3><p>The ERC20 standard defines six mandatory functions that a token must have:</p><ul><li>TotalSupply: This function returns the total number of tokens ever issued.</li><li>BalanceOf: The BalanceOf function allows users to check the balance of a specific token owner’s account.</li><li>Transfer: The Transfer function automatically transfers a specified number of tokens to a designated address.</li><li>TransferFrom: This function allows the automatic transfer of a specified number of tokens from one address to another.</li><li>Approve: The Approve function grants permission to a designated address to withdraw a specific number of tokens from the token owner’s account.</li><li>Allowance: The Allowance function returns the number of tokens approved for withdrawal by a spender from the token owner’s account.</li></ul><p>These functions provide a standard interface for ERC20 tokens, ensuring i<strong>nteroperability</strong>, <strong>security</strong>, and <strong>ease of use</strong> within the <a href="https://ethereum.org/en/">Ethereum ecosystem</a>.</p><h3>ERC20 Events</h3><p>In addition to functions, ERC20 tokens also include two mandatory events:</p><ul><li>Transfer: The Transfer event is triggered when a transfer of tokens is successfully executed.</li><li>Approval: The Approval event logs the approval of a specific address to spend a certain number of tokens.</li></ul><p>These events help keep track of token transfers and approvals within the blockchain.</p><h3>Use Cases of ERC-20 Tokens</h3><p>ERC-20 tokens have a wide range of applications, including:</p><ul><li><strong>Cryptocurrencies &amp; Payments</strong> — ERC20 tokens as digital assets used for seamless transactions (e.g., USDT, DAI).</li><li><strong>Decentralized Finance (DeFi)</strong> — ERC20 tokens are used for power lending, staking, and yield farming (e.g., AAVE, UNI)</li><li><strong>Utility Tokens</strong>: Tokens used for accessing services or platforms (e.g., BAT for Brave Browser, LINK for Chainlink).</li><li><strong>Governance Tokens</strong> — Voting power in decentralized projects (e.g., COMP for Compound, MKR for MakerDAO)</li><li><strong>Stablecoins</strong>: Tokens like DAI, BUSD and USDC are ERC-20 tokens pegged to fiat currencies with real-world value.</li><li><strong>Fundraising (ICOs and IDOs)</strong>: Projects raise capital by issuing ERC-20 tokens to investors, this has helped revolutionize crowdfunding.</li><li><strong>Soulbound Tokens (SBTs)</strong> — These are non-transferable ERC20 tokens used for identity, reputation, or credentials in Web3.</li></ul><h3>Examples of dApps Using ERC-20 Tokens</h3><p>Some popular dApps leveraging ERC-20 tokens include:</p><ul><li><strong>Uniswap</strong> (Decentralized Exchange): Uniswap is a decentralized exchange that facilitates the swapping of ERC-20 tokens instantly. It uses ERC-20 tokens for liquidity pools and token swaps. Users can add liquidity in the form of ERC-20 tokens to earn fees.</li><li><strong>MakerDAO (</strong>Decentralized Stablecoin System) : MakerDAO allows users to lock up collateral in the form of ERC-20 tokens to mint DAI, a decentralized stablecoin. The DAI token is an ERC-20 token, and the system itself is built around the minting and management of ERC-20 tokens.</li><li><strong>Aave</strong> (DeFi Lending): Aave allows users to lend and borrow ERC-20 tokens. It also has unique features like Flash Loans and liquidity pools, all of which are built on ERC-20 tokens.</li><li><strong>Yearn Finance (</strong>Yield Aggregator) : Yearn Finance uses ERC-20 tokens to allow users to participate in its yield farming protocols. It optimizes yield for users by automatically shifting their funds across various DeFi protocols.</li><li><strong>Compound</strong> (DeFi Lending): Compound allows users to supply and borrow ERC-20 tokens. The platform issues cTokens (e.g., cETH for Ethereum, cDAI for DAI) in exchange for deposited assets. These cTokens are ERC-20 tokens themselves and represent a user’s share in the liquidity pool.</li><li><strong>Decentraland</strong> (Metaverse): Uses MANA, an ERC-20 token, for virtual asset purchases.</li></ul><h3>Code Explanation: Implementing an ERC-20 Token from Scratch</h3><p>To fully understand ERC-20, we will implement a basic ERC-20 token without using OpenZeppelin. Below is a step-by-step breakdown with code snippets.</p><h3>The ERC-20 Token Structure</h3><p>Our custom ERC-20 token contract consists of the following key components:</p><ul><li>State variables to store token metadata and balances.</li><li>Event declarations for logging transactions.</li><li>Modifiers for access control.</li><li>The constructor for initializing the token.</li><li>Core ERC-20 functions: transfer, approve, transferFrom.</li><li>Additional features: burn, mint, increaseAllowance, decreaseAllowance.</li><li>Getter Functions: name, symbol, decimals, allowance,totalSupply, balanceOf, and owner.</li></ul><h3>1. State Variables</h3><pre>string private _name;<br>string private _symbol;<br>uint8 private _decimals;<br>address private _owner;<br>uint256 private _totalSupply;<br><br><br>mapping(address =&gt; uint256) private balances;<br>mapping(address =&gt; mapping(address =&gt; uint256)) private allowances;</pre><p>These variables store the token’s name, symbol, decimal places, total supply, and ownership details. The balances mapping tracks each address&#39;s token balance, while allowances enables delegated spending.</p><h3>2. Events</h3><pre>event Transfer(address indexed _from, address indexed _to, uint256 _value);<br>event Approval(address indexed _owner, address indexed _spender, uint256 _value);<br>event Burn(address indexed _from, uint256 _value);<br>event Mint(address indexed _to, uint256 _value);</pre><p>Events are emitted to log important transactions such as token transfers, approvals, burning, and minting.</p><h3>3. Modifiers</h3><p>Modifiers help enforce rules in functions.</p><pre>modifier onlyOwner() {<br>        if (msg.sender != _owner) revert OnlyOwnerAllowed();<br>        _;<br>    }</pre><ul><li>onlyOwner modifier ensures only the contract owner can perform certain actions.</li></ul><h3>4. Constructor</h3><pre>constructor(string memory name_, string memory symbol_, uint8 decimals_, uint256 initialSupply_) {  <br>    _name = name_;<br>    _symbol = symbol_;<br>    _decimals = decimals_;<br>    _owner = msg.sender;<br>    _totalSupply = initialSupply_ * 10 ** uint8(_decimals);<br>    balances[msg.sender] = _totalSupply;<br>    emit Transfer(address(0), msg.sender, _totalSupply);<br>}</pre><p>The constructor initializes the token with the provided details and assigns the entire initial supply to the contract deployer.</p><h3>5. Core ERC-20 Functions</h3><h4>Transfer Tokens</h4><pre>function transfer(address _to, uint256 _value) public returns (bool) {<br>    if (_to == address(0)) revert InvalidAddress();<br>    if (_value &lt;= 0) revert InvalidAmount();<br>    if (balances[msg.sender] &lt; _value) revert InsufficientFunds();<br>    <br>    balances[msg.sender] -= _value;<br>    balances[_to] += _value;<br><br>    emit Transfer(msg.sender, _to, _value);<br>    return true;<br>}</pre><p>This function allows users to send tokens to another valid address while ensuring the sender has sufficient funds.</p><h4>Approve Spending</h4><pre>function approve(address _spender, uint256 _value) public returns (bool) {<br>    if (_spender == address(0)) revert InvalidAddress();<br>    if (_value &lt;= 0) revert InvalidAmount();<br>    if (balances[msg.sender] &lt; _value) revert InsufficientFunds();<br>    allowances[msg.sender][_spender] = _value;<br>    emit Approval(msg.sender, _spender, _value);<br>    return true;<br>}</pre><p>This function allows users to grant spending permission to another address.</p><h4>Transfer From (Delegated Spending)</h4><pre>function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {<br>    if (_to == address(0)) revert InvalidAddress();<br>    if (_value &lt;= 0) revert InvalidAmount();<br>    if (balances[_from] &lt; _value) revert InsufficientFunds();<br>    if (allowances[_from][msg.sender] &lt; _value) revert InsufficientAllowance();<br>    <br>    balances[_from] -= _value;<br>    balances[_to] += _value;<br>    allowances[_from][msg.sender] -= _value;<br>    <br>    emit Transfer(_from, _to, _value);<br>    return true;<br>}</pre><p>This function enables an approved spender to transfer tokens on behalf of the owner.</p><h3>6. Additional Features</h3><h4>Burning Tokens</h4><pre>function burn(uint256 _value) public returns (bool) {<br>    if (balances[msg.sender] &lt; _value) revert InsufficientFunds();<br>    if (_value &lt;= 0) revert InvalidAmount();<br><br>    balances[msg.sender] -= _value;<br>    _totalSupply -= _value;<br>    <br>    emit Burn(msg.sender, _value);<br>    emit Transfer(msg.sender, address(0), _value);<br>    return true;<br>}</pre><p>The burn function permanently removes tokens from circulation, reducing total supply.</p><h4>Minting Tokens</h4><pre>function mint(address _to, uint256 _value) public onlyOwner returns (bool) {<br>    if (_to == address(0)) revert InvalidAddress();<br>    if (_value &lt;= 0) revert InvalidAmount();<br><br>    _totalSupply += _value;<br>    balances[_to] += _value;<br>    <br>    emit Mint(_to, _value);<br>    emit Transfer(address(0), _to, _value);<br>    return true;<br>}</pre><p>The mint function allows the owner to generate new tokens and assign them to a specified address.</p><h3>7. Getter Functions</h3><p>Since we made our state variables private we have to write getter functions to be able to call them.</p><pre>function name() public view returns (string memory) {<br>        return _name;<br>    }<br><br>    function symbol() public view returns (string memory) {<br>        return _symbol;<br>    }<br><br>    function decimals() public view returns (uint8) {<br>        return _decimals;<br>    }<br><br>    function totalSupply() public view returns (uint256) {<br>        return _totalSupply;<br>    }<br><br>    function owner() public view returns (address) {<br>        return _owner;<br>    }<br><br>    function balanceOf(address _account) public view returns (uint256) {<br>        if (_account == address(0)) revert InvalidAddress();<br>        return balances[_account];<br>    }<br><br>    function allowance(address _accountOwner, address _spender) public view returns (uint256) {<br>        if (_spender == address(0)) revert InvalidAddress();<br>        return allowances[_accountOwner][_spender];<br>    }</pre><h3>Conclusion</h3><p>ERC-20 tokens form the foundation of the Ethereum ecosystem, driving everything from DeFi to NFTs and metaverse economies. By implementing an ERC-20 token contract from scratch, we gain insight into how token balances, approvals, and transactions work under the hood. This contract provides a foundational understanding that can be extended with additional features such as staking, governance, and yield farming integrations.</p><p>🔗 <strong>Follow me on Medium for more blockchain insights!</strong></p><p>🔗 <strong>Check my </strong><a href="https://github.com/7maylord/ERC20-Token.git"><strong>Github</strong></a><strong> for the full code implementation!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c21de077cf2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum Private Keys: Your Super-Secret Crypto Passport]]></title>
            <link>https://maylord.medium.com/ethereum-private-keys-your-super-secret-crypto-passport-f0983d632e53?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0983d632e53</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[newbie]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[private-key]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 23:06:26 GMT</pubDate>
            <atom:updated>2025-02-04T23:06:26.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bVDH641K7T1C4oyU" /><figcaption>Photo by <a href="https://unsplash.com/@kanchanara?utm_source=medium&amp;utm_medium=referral">Kanchanara</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Hey Newbie! Let’s Talk Private Keys</h3><p>So, you just hopped onto the Ethereum train, and everyone keeps shouting, <strong>“Never share your private key!”</strong> But what the heck is a private key? Is it an actual key? Can I put it on a keychain? Do I need to whisper it to my pet for safekeeping? Let’s break it down in a way that won’t put you to sleep.</p><h3>What Even is a Private Key?</h3><p>A <strong>private key</strong> is basically your ultra-secret, crypto password. It’s a <strong>really, really big random number</strong> that lets you access your Ethereum wallet. Imagine it as a VIP backstage pass to your crypto concert — if someone else gets it, they’re taking all your ETH and eating your snacks too because those hackers would take your sepolia too.</p><h3>Example of a Private Key (But Not a Real One, Don’t Get Excited):</h3><pre>0x8f2a559490b9a996a4e9b5a1e49a1c1c4b7f105f040ea2580dc2f71d208c0a3a</pre><p>If this looks like a bunch of random gibberish, that’s because <strong>it is</strong> — but it’s powerful gibberish.</p><h3>How Are Private Keys Created?</h3><p>Ethereum private keys are whipped up using fancy cryptographic juju. Here’s how:</p><h3>Step 1: Generate a Super-Random 256-bit Number</h3><p>A private key is just a number between:</p><pre>1 and 2²⁵⁶ - 1 (basically, bigger than your weekend pizza order)</pre><p>Some techy magic (like RAND_bytes()in OpenSSL, crypto.getRandomValues() in JavaScript or secrets.token_bytes(32) in Python) makes sure it’s truly random and secure.</p><h3>Step 2: Turn It Into a Public Key</h3><p>Ethereum uses <strong>Elliptic Curve Cryptography (ECC)</strong> — specifically, the <strong>secp256k1 curve</strong>. This is some fancy math, you don’t need to understand it — just know that math geniuses made it super safe. The public key is derived by multiplying the private key by a special point (G) on the curve:</p><pre>Public Key = Private Key × G</pre><p>This process is <strong>one-way</strong> — meaning you <strong>cannot</strong> reverse it to get the private key from the public key.</p><p>✅ <strong>Example of a Public Key (Still Not a Real One, Don’t Copy-Paste This!):</strong></p><pre>0x04c9a2f8e9c076e57cb60d948ac4a0f0e89fba0a5f8bfaeb49f24d9c5e0f6b34f8e4d849e0e91e94d9819d5f90f5f1b70c09b9d4a9d4f2ed4d9c9a88be8e5b8e91</pre><p>This thing is <strong>128 characters long</strong> and exists to eventually create your Ethereum address.</p><h3>How Your Ethereum Address is Born</h3><p>Your Ethereum address is your public-facing crypto identity. Think of it like your <strong>crypto username</strong> — you share it with people so they can send you ETH. Here’s how it’s made:</p><h3>Step 1: Hash That Public Key with Keccak-256</h3><ul><li>Remove the 0x04 prefix from the public key (because it’s just extra fluff).</li><li>Smash it through <strong>Keccak-256 hashing</strong> like a blender making a crypto smoothie.</li></ul><h3>Step 2: Keep the Last 20 Bytes</h3><ul><li>Take only the last <strong>40 hex characters</strong> (20 bytes) from the Keccak hash, affix the prefix 0x and BOOM — you have your Ethereum address!</li></ul><p>✅ <strong>Example Ethereum Address (Yes, This One Looks More Familiar!):</strong></p><pre>0x6Ff44e3B1129b136e5C1f32C6Dd6E6219eB0b3f6</pre><p>This is the magic string you give people when they want to send you ETH.</p><h3>How to Keep Your Private Key Safe (Or Else 😱)</h3><ul><li><strong>Never, ever, ever share it!</strong> Not even with your grandma.</li><li><strong>Use a hardware wallet</strong> — because hackers are smarter than your antivirus software.</li><li><strong>Back it up somewhere super safe</strong> — but maybe not written on a napkin.</li><li><strong>If you lose it, no one — not even Vitalik Buterin — can help you.</strong> Ethereum has no password reset button!</li></ul><h3>📌 Summary</h3><p>Your <strong>private key</strong> is your <strong>golden ticket</strong> to crypto. Keep it secret, keep it safe, and <strong>don’t be that person who loses their ETH forever!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0983d632e53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Step Form: My Frontend Mentor Assignment for Web3Bridge]]></title>
            <link>https://maylord.medium.com/building-multi-step-form-my-frontend-mentor-assignment-for-web3bridge-c3435a64b7c7?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3435a64b7c7</guid>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 15:06:33 GMT</pubDate>
            <atom:updated>2024-09-02T15:06:33.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Hello, I’m Olumide, a passionate web developer actively honing my skills through hands-on projects and challenges. As a developer, there’s always a thrill in solving real-world problems with code. In this blog post, I’ll walk you through how I built a dynamic multi-step subscription form for the Frontend Mentor assignment with Web3Bridge. The goal was to create a user-friendly form that allows users to select a plan, choose add-ons, and review their choices before confirming their subscription.</p><h4>The Challenge</h4><p>The task was to create a multi-step form that guides users through several steps to select a subscription plan, choose add-ons, and confirm their selection before submission. Each step had to be interactive, visually appealing, and provide clear feedback to the user.</p><p>Here’s a breakdown of the main features:</p><ul><li><strong>Personal Info Validation:</strong> Users input their name, email, and phone number in the first step, with validation to ensure all fields are correctly filled.</li><li><strong>Plan Selection:</strong> In the second step, users choose between monthly or yearly subscription plans, with prices updating dynamically.</li><li><strong>Add-Ons Selection:</strong> The third step allows users to select additional features, with the total price recalculated accordingly.</li><li><strong>Summary and Confirmation:</strong> The final step displays a summary of the selected plan and add-ons before submission.</li></ul><h3>Development Process</h3><h4>Planning &amp; Setup</h4><p>Before jumping into the code, I spent some time planning the project. I broke down the design into individual components, such as the form steps, plan cards, and add-on options. This approach made it easier to manage the complexity and ensured that each part of the form could be developed and tested independently.</p><p><strong>HTML Structure</strong></p><p>The form’s HTML structure was straightforward, with each step wrapped in a &lt;div&gt; element, and navigation buttons at the bottom of each section. Here&#39;s a simplified version:</p><pre>  &lt;body&gt;<br>    &lt;main class=&quot;main&quot;&gt;<br>      &lt;!-- WRAPPER --&gt;<br>      &lt;div class=&quot;step-container&quot;&gt;<br>        &lt;!-- SIDEBAR --&gt;<br>        &lt;div class=&quot;sidebar&quot;&gt;<br>          &lt;!-- Side Indicator div go here --&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;!-- form steps container --&gt;<br>        &lt;div class=&quot;steps-container&quot;&gt;<br>          &lt;!-- step1 --&gt;<br>          &lt;form class=&quot;step&quot; id=&quot;form&quot;&gt;<br>            &lt;!-- Personal Info go here --&gt;<br>          &lt;/form&gt;<br>          &lt;!-- STEP 2 --&gt;<br>          &lt;div class=&quot;step&quot; id=&quot;step-2&quot;&gt;<br>            &lt;h3 class=&quot;main-title&quot;&gt;Select your plan&lt;/h3&gt;<br>            &lt;p class=&quot;description&quot;&gt;<br>              You have the option of monthly or yearly billing.<br>            &lt;/p&gt;<br>            &lt;div class=&quot;plan-card-container&quot; id=&quot;plan-cards&quot;&gt;<br>              &lt;!-- Plan cards go here --&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;!-- STEP 3 --&gt;<br>          &lt;div class=&quot;step&quot; id=&quot;step-3&quot;&gt;<br>            &lt;h3 class=&quot;main-title&quot;&gt;Pick add-ons&lt;/h3&gt;<br>            &lt;p class=&quot;description&quot;&gt;<br>              Add-ons help enhance your gaming experience.<br>            &lt;/p&gt;<br>            &lt;div class=&quot;addson-card_container&quot;&gt;<br>              &lt;div class=&quot;addon-card card&quot;&gt;<br>                &lt;input type=&quot;checkbox&quot; name=&quot;checkbox&quot; class=&quot;checkbox&quot; /&gt;<br>                &lt;div class=&quot;card-text&quot;&gt;<br>                  &lt;p class=&quot;card-name&quot;&gt;Online service&lt;/p&gt;<br>                  &lt;p class=&quot;card-description&quot;&gt;Access to multiplayer games&lt;/p&gt;<br>                &lt;/div&gt;<br>                &lt;p class=&quot;card-price&quot;&gt;<br>                  +$&lt;span class=&quot;subscription-price&quot;&gt;00&lt;/span&gt;/&lt;span<br>                    class=&quot;subscription-duration&quot;<br>                    &gt;xx&lt;/span<br>                  &gt;<br>                &lt;/p&gt;<br>              &lt;/div&gt;<br>              &lt;div class=&quot;addon-card card&quot;&gt;<br>                &lt;!-- Add-On cards go here --&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;!-- STEP 4 --&gt;<br>          &lt;div class=&quot;step&quot; id=&quot;step-4&quot;&gt;<br>            &lt;h3 class=&quot;main-title&quot;&gt;Finishing up&lt;/h3&gt;<br>            &lt;p class=&quot;description&quot;&gt;<br>              Double-check everything looks OK before confirming.<br>            &lt;/p&gt;<br>            &lt;div class=&quot;summary-container card&quot;&gt;<br>              &lt;div class=&quot;selected-plan-container&quot;&gt;<br>                &lt;div class=&quot;&quot; id=&quot;selected-plan&quot;&gt;&lt;!-- selected plan --&gt;&lt;/div&gt;<br>                &lt;button class=&quot;change-plan&quot; id=&quot;change-plan&quot;&gt;change&lt;/button&gt;<br>              &lt;/div&gt;<br>              &lt;ul id=&quot;selected-addon&quot;&gt;<br>                &lt;!-- selected adds-on --&gt;<br>              &lt;/ul&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;total&quot; id=&quot;total&quot;&gt;<br>              &lt;!-- total amount --&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;!-- last step | thank you --&gt;<br>          &lt;div class=&quot;step last-step&quot; id=&quot;thank-you&quot;&gt;<br>            &lt;!-- thank you message go here --&gt;<br>          &lt;/div&gt;<br>          &lt;!-- BUTTON --&gt;<br>          &lt;div class=&quot;button-container&quot;&gt;<br>            &lt;button class=&quot;button prev-button&quot; id=&quot;prev-button&quot;&gt;Go Back&lt;/button&gt;<br>            &lt;button type=&quot;submit&quot; class=&quot;button next-button&quot; id=&quot;next-button&quot;&gt;<br>              Next Step<br>            &lt;/button&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/main&gt;<br>  &lt;/body&gt;</pre><p><strong>Styling with CSS</strong></p><p>I kept the CSS clean and modular, with styles for each step and the form controls. I focused on responsiveness to ensure the form looks good on all devices. I used Flexbox and Grid for layout and transitions to enhance the form’s interactivity.</p><pre>.main {<br>    max-width: 1050px;<br>    min-height: 100vh;<br>    width: 100%;<br>    margin: 0 auto;<br>    display: flex;<br>    align-items: center;<br>    justify-content: center;<br>    background-color: var(--Magnolia);<br>    place-self: center;<br>}<br><br>@media (max-width: 768px) {<br>    .main {<br>        align-items: flex-start;<br>    }<br>}</pre><pre>.step {<br>  display: none;<br>}<br>.step.active {<br>display: inline-block;<br>}</pre><pre>.button-container {<br>    display: flex;<br>    justify-content: space-between;<br>    align-items: center;<br>}<br><br>.button {<br>    border: none;<br>    outline: none;<br>    cursor: pointer;<br>    font-weight: 500;<br>    padding: 10px 15px;<br>    border-radius: 5px;<br>}<br><br>.next-button {<br>    color: var(--Light-gray);<br>    background-color: var(--Marine-blue);<br>}<br><br>.next-button:hover {<br>    transition: background 0.3s;<br>    background-color: var(--Purplish-blue);<br>}<br><br>.prev-button {<br>    color: var(--Cool-gray);<br>    background-color: var(--White);<br>    padding: 0;<br>}<br><br>.prev-button:hover {<br>    color: var(--Marine-blue);<br>}</pre><p><strong>JavaScript Functionality</strong></p><p>The magic happened in the JavaScript. Here’s a summary of the key functions:</p><ul><li><strong>Step Navigation:</strong> I implemented event listeners on the “Next” and “Previous” buttons to move between form steps, with validation checks at each step.</li></ul><pre>const nextBtn = document.getElementById(&#39;next-button&#39;);<br>const prevBtn = document.getElementById(&#39;prev-button&#39;);<br>let stepNum = 0;<br><br>// declare function for show warning text when plan not selected and next button pressed<br>const selectPlanError = (text) =&gt; {<br>  document.getElementById(&#39;select-plan-error&#39;).textContent = text;<br>};<br><br>// handle next step button<br>nextBtn.addEventListener(&#39;click&#39;, (e) =&gt; {<br>  e.preventDefault();<br>  if (stepNum === 0) {<br>    // form validation<br>    if (!formValidation()) return;<br>    stepNum++;<br>    showStep(stepNum);<br>  } else if (stepNum === 1) {<br>    // show warning if plan not selected<br>    if (Object.entries(selectedPlan).length === 0) {<br>      return selectPlanError(&#39;Please select a plan&#39;);<br>    }<br>    stepNum++;<br>    showStep(stepNum);<br>  } else if (stepNum === 2) {<br>    // render list of selected plan and add-on with price<br>    renderTotal();<br>    stepNum++;<br>    showStep(stepNum);<br>  } else if (stepNum === 3) {<br>    stepNum++;<br>    showStep(stepNum);<br>  } else return;<br>});<br><br>// handle previous step button<br>prevBtn.addEventListener(&#39;click&#39;, (e) =&gt; {<br>  e.preventDefault();<br>  stepNum--;<br>  return showStep(stepNum);<br>});<br>     </pre><ul><li><strong>Form Validation:</strong> A formValidation function checks the validity of the input fields in the first step. If any input is invalid, an error message is displayed.</li></ul><pre>const formValidation = () =&gt; {<br>  // check all inputs are valid using forEach loop<br>  formInput.forEach((input) =&gt; {<br>    // username<br>    if (input.name === &#39;userName&#39;) {<br>      return input.value.length === 0<br>        ? showError(input, &#39;Enter your name&#39;)<br>        : hideError(input);<br>    }<br>    // email<br>    if (input.name === &#39;email&#39;) {<br>      // verify email input value using regex<br>      const emailRegExp = new RegExp(&#39;[a-z0-9]+@[a-z]+.[a-z]{2,3}&#39;);<br>      return input.value.length === 0<br>        ? showError(input, &#39;Enter email&#39;)<br>        : !emailRegExp.test(input.value)<br>        ? showError(input, &#39;Enter valid email&#39;)<br>        : hideError(input);<br>    }<br>    // phone number<br>    if (input.name === &#39;phone&#39;) {<br>      return input.value.length === 0<br>        ? showError(input, &#39;Enter your mobile number&#39;)<br>        : hideError(input);<br>    }<br>  });<br>  // return form validity<br>  return form.checkValidity();<br>};</pre><ul><li><strong>Plan Selection:</strong> Users can toggle between monthly and yearly plans, with the prices updating accordingly. I used an array to store the plan prices and dynamically update the DOM based on user selection.</li></ul><pre>planCards.forEach((card) =&gt; {<br>  card.addEventListener(&#39;click&#39;, (e) =&gt; {<br>    selectPlanError(&#39;&#39;);<br>    let target = e.currentTarget;<br>    // remove selected class of all cards<br>    planCards.forEach((card) =&gt; card.classList.remove(&#39;selected&#39;));<br>    // add selected class to the current card<br>    target.classList.add(&#39;selected&#39;);<br><br>    // store selected plan name, price and duration<br>    let planName = target.querySelector(&#39;.card-name&#39;).textContent;<br>    let planPrice = target.querySelector(&#39;.subscription-price&#39;).textContent;<br>    let planDur = target.querySelector(&#39;.subscription-duration&#39;).textContent;<br><br>    // add selected plan details to the selectedPlan object<br>    return (selectedPlan = { planName, planPrice, planDur });<br>  });<br>});</pre><ul><li><strong>Add-Ons Selection:</strong> Similar to the plan selection, I handled add-ons by allowing users to select multiple options, and the total price updates in real time.</li></ul><pre>addOnsCards.forEach((card) =&gt; {<br>  // add event listener to the add-on cards<br>  card.addEventListener(&#39;click&#39;, (e) =&gt; {<br>    let target = e.currentTarget;<br>    let checkbox = target.querySelector(&#39;.checkbox&#39;);<br>    // add selected class to the card<br>    target.classList.toggle(&#39;selected&#39;);<br><br>    // checked box checked if box is selected<br>    if (target.classList.contains(&#39;selected&#39;)) {<br>      return (checkbox.checked = true);<br>    } else {<br>      return (checkbox.checked = false);<br>    }<br>  });<br>});</pre><ul><li><strong>Summary Rendering:</strong> The final step shows a summary of the selected plan and add-ons, including the total price. This step reinforces the user’s choices before they submit the form</li></ul><h4>Challenges and Solutions</h4><p>One of the biggest challenges was fixing the toggle functionality to dynamically render prices. The goal was to have the form update plan and add-on prices based on whether the user selected monthly or yearly billing. Initially, this was not working as expected, leading to some frustration, I checked the code responsible for toggling between billing cycles and realized I needed to better manage state changes for both plans and add-ons. By restructuring the event listener I was able to make the dynamic pricing work well.</p><p>Validation was another tricky part, especially when ensuring that users didn’t skip required fields. To address this, I implemented validation checks and provided immediate feedback to the user.</p><h4>Final Thoughts</h4><p>Building this multi-step form was a rewarding experience. If you’re interested in building a similar form, I recommend starting with a clear structure in your HTML, maintaining clean CSS, and writing modular JavaScript. I’m excited to continue working on similar challenges and expanding my front-end development expertise.</p><p>Here’s a <a href="https://7maylord.github.io/multi-step-form/">link to the live demo</a> of the project, where you can see it in action.</p><h3>Conclusion</h3><p>Taking on this challenge was not only a great way to improve my frontend development skills but also a fulfilling experience in creating something tangible from scratch. If you’re a developer looking to enhance your skills, I highly recommend tackling a Frontend Mentor challenge.</p><p>Thank you for reading! If you have any feedback on the project or just want to connect, feel free to reach out. You can also check out the project repository <a href="https://github.com/7maylord/multi-step-form.git">here</a> and follow me for more content on web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3435a64b7c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing a Backend Problem: My HNG 11 Journey ‍]]></title>
            <link>https://maylord.medium.com/fixing-a-backend-problem-my-hng-11-journey-a97d173bc766?source=rss-2e07889334d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a97d173bc766</guid>
            <category><![CDATA[websocket-api]]></category>
            <category><![CDATA[hng11]]></category>
            <category><![CDATA[hnginternship]]></category>
            <dc:creator><![CDATA[Adenigba Olumide]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 20:37:51 GMT</pubDate>
            <atom:updated>2024-06-28T20:37:51.334Z</atom:updated>
            <content:encoded><![CDATA[<p>As a backend developer, solving tricky problems are a part of the job. Recently, I faced an issue while building a restaurant chatbot app, the app was losing its conversation data. Here i explained how the issue was fixed.</p><p>The chatbot app was using socket.io to enable real-time bidirectional event-based communication but the problem was data persisting, whenever the I refreshed the server or the page the conversation data was forgotten. This happened because I was not using any database to store my data because when i started building the app it was just to understand websockets and its application use, I soon added other functionalities that required me to store my data atleast for a 24 hour window.</p><p>So i decided to use session storage with express and memorystore, which stored the data temporarily in memory. This setup helped retain the order history data for 24 hours even if the server restarts.</p><p>First, I installed the necessary packages for session handling:</p><pre>npm install express-session memorystore</pre><p>next, I set up the session middleware in the app to properly handle session data:</p><pre>const session = require(&#39;express-session&#39;);<br>const MemoryStore = require(&#39;memorystore&#39;)(session);<br>const dotenv = require(&quot;dotenv&quot;);<br><br>dotenv.config();<br><br><br>const sessionMiddleware = session({<br>  // configuration for session middleware<br>  store: new MemoryStore({checkPeriod: 86400000}),// prune expired entries every 24h<br>    secret: process.env.SESSION_SECRET,<br>    resave: false,<br>    saveUninitialized: true,<br>    cookie: { maxAge: 24 * 60 * 60 * 1000 } // 1 day<br>});<br><br>module.exports = sessionMiddleware;</pre><p>after that, I updated my code to store and retrieve session data properly, ensuring it maintained the conversation context,</p><pre>const { getMenuItems, handleUserMessage, sendOptions } = require(&#39;./database.js&#39;);<br>const session = require(&#39;express-session&#39;);<br>const MemoryStore = require(&#39;memorystore&#39;)(session);<br>const sessionMiddleware = require(&#39;./middleware.js&#39;);<br><br><br>function setupSocket(io) {<br>    io.use((socket, next) =&gt; {<br>        sessionMiddleware(socket.request, socket.request.res || {}, next);<br>    });<br><br><br>    io.on(&#39;connection&#39;, (socket) =&gt; {<br>        console.log(&#39;New client connected&#39;, socket.id);<br><br>        const session = socket.request.session;<br>        //Initialize session for the new user<br>        if (!session.currentOrder) {<br>            session.currentOrder = [];<br>        }<br>        if (!session.orderHistory) {<br>            session.orderHistory = [];<br>        }<br><br>        // Save session data<br>        session.save();<br>        <br>        // Send initial options to the user<br>        socket.emit(&#39;message&#39;, &#39;Welcome to the Restaurant Chatbot!&#39;)<br>        sendOptions(socket);<br><br>        socket.on(&#39;message&#39;, (message) =&gt; {<br>            try {<br>                console.log(`Received: ${message}`, socket.id);<br>                handleUserMessage(socket, message, session); // Pass session data<br>                <br>            } catch (error) {<br>                console.error(&#39;Error handling message:&#39;, error);<br>                socket.emit(&#39;message&#39;, &#39;Sorry, there was an error processing your message. Please try again.&#39;);<br>            }<br>        });<br><br>        socket.on(&#39;disconnect&#39;, () =&gt; {<br>            console.log(&#39;Client disconnected&#39;, socket.id);<br>        });<br>    });<br>}<br><br><br><br>module.exports = { setupSocket };</pre><p>here is the <a href="https://github.com/7maylord/Restaurant_ChatBot">link</a> to the repository of my chatbot app.</p><p>Honestly speaking, fixing this issue taught me a lot more about session management as it made the chatbot more reliable and improved its performance.</p><p>Finally, I will be starting the HNG11 Internship. I am looking forward to the the chance to work and network with other talented developers. If you’re curious about the HNG Internship, you can also apply here <a href="https://hng.tech/internship">official website</a> and <a href="https://hng.tech/premium">premium programs</a> for a chance to be part of this amazing community.</p><p>Stay tuned for more updates on my journey and the challenges I’ll be tackling during the internship!</p><p>Until next time. Sayonara!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a97d173bc766" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>