<?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 foobarbaz on Medium]]></title>
        <description><![CDATA[Stories by foobarbaz on Medium]]></description>
        <link>https://medium.com/@itsme24543?source=rss-1f2c8ca41f52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NUTBtZd3mnvfvy8Q</url>
            <title>Stories by foobarbaz on Medium</title>
            <link>https://medium.com/@itsme24543?source=rss-1f2c8ca41f52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:33:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itsme24543/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[Option Trading Strategies Guide: CRWD Applied Examples]]></title>
            <link>https://medium.com/@itsme24543/option-trading-strategies-guide-crwd-applied-examples-5d39b86313f0?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d39b86313f0</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 02:25:06 GMT</pubDate>
            <atom:updated>2026-08-10T02:25:06.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Full credit to <strong>Tom Sosnoff (amazign stuff from him ) </strong><a href="https://www.youtube.com/watch?v=Z__VENA80Bo">https://www.youtube.com/watch?v=Z__VENA80Bo</a></p><p><strong>CrowdStrike ($CRWD)</strong> baseline market conditions for these setups:</p><ul><li><strong>Underlying Stock Price:</strong> <strong>~$214.00 (Aug 9th,2026)</strong></li><li><strong>Expected Move / Implied Volatility:</strong> ±8% to 10% expected move ($17.00 — $21.00 move; expected downside floor ~$195.00, upside cap ~$235.00).</li></ul><h3>1. Short Puts (0:28–1:17)</h3><p><strong>Concept:</strong> Selling an out-of-the-money (OTM) cash-secured put at or near the expected downside move to collect premium with high probability of profit.</p><ul><li><strong>CRWD Setup:</strong> Sell <strong>$195 Put</strong> (~16–20 Delta) for a <strong>$3.50 credit</strong>.</li><li><strong>Max Loss:</strong> $19,150 (Strike — Credit collected × 100).</li><li><strong>Max Profit:</strong> $350 (Premium collected).</li><li><strong>Breakeven:</strong> $191.50 ($195.00 — $3.50).</li></ul><pre>Profit / Loss<br>             ▲<br>     +$350   │─────────────────────── Max Profit<br>             │                      /<br>             │                     /<br>         $0  ┼────────────────────┴─────► CRWD Price<br>             │                   / $195.00<br>             │                  / (Strike)<br>             │                 /<br>             │    Breakeven: $191.50<br>             ▼</pre><h3>2. Jade Lizard (1:17–2:24)</h3><p><strong>Concept:</strong> Combining a short OTM put with a short call spread (bear call spread) configured so the total net credit collected is greater than the width of the call spread, eliminating upside risk.</p><ul><li><strong>CRWD Setup:</strong></li><li>Sell $195 Put for $3.50 credit</li><li>Sell $230 Call for $3.00 credit</li><li>Buy $235 Call for $1.50 debit</li><li><strong>Total Net Credit:</strong> $5.00 ($3.50 + $3.00 — $1.50)</li><li><strong>Call Spread Width:</strong> $5.00 ($235 — $230).</li><li><strong>Max Loss Upside:</strong> <strong>$0.00</strong> (Width of spread $5.00 — Net Credit $5.00).</li><li><strong>Max Loss Downside:</strong> $19,000 ($195 Put Strike — $5.00 credit × 100).</li></ul><pre>Profit / Loss<br>             ▲<br>     +$500   │         ┌─────────────┐ Max Profit ($500)<br>             │        /               \<br>         $0  ┼───────┼─────────────────┴────────► CRWD Price<br>             │      / $195           $230  $235<br>             │     /<br>             ▼   Breakeven: $190.00 (No upside risk zone)</pre><h3>3. Covered Calls (2:24–4:01)</h3><p><strong>Concept:</strong> Holding 100 shares of underlying stock while simultaneously selling an OTM call option at a 25–30 Delta to generate yield and lower the cost basis.</p><ul><li><strong>CRWD Setup:</strong></li><li>Buy 100 shares of CRWD @ <strong>$214.00</strong> ($21,400 investment)</li><li>Sell <strong>$225 Call</strong> (~30 Delta) for a <strong>$4.50 credit</strong></li><li><strong>Net Cost Basis:</strong> $209.50 per share ($214.00 — $4.50).</li><li><strong>Max Profit:</strong> $1,550 [($225 Strike — $209.50 Basis) × 100] if CRWD expires at or above $225.</li></ul><pre>Profit / Loss<br>             ▲<br>    +$1,550  │                  ┌───────────── Max Profit<br>             │                 /<br>             │                /<br>         $0  ┼───────────────┼────────────────► CRWD Price<br>             │              / $225.00<br>             │             /<br>             │  Breakeven: $209.50<br>             ▼</pre><h3>4. Short Put Spreads (4:01–5:20)</h3><p><strong>Concept:</strong> A defined-risk bull put spread where you sell a higher-strike OTM put and buy a lower-strike OTM put for protection.</p><ul><li><strong>CRWD Setup:</strong></li><li>Sell $195 Put</li><li>Buy $185 Put</li><li><strong>Net Credit Collected:</strong> <strong>$2.00</strong> ($200 per contract)</li><li><strong>Max Profit:</strong> $200 (Net credit).</li><li><strong>Max Loss:</strong> $800 [($195 — $185 Strike Width) — $2.00 Credit × 100].</li><li><strong>Breakeven:</strong> $193.00.</li></ul><pre>Profit / Loss<br>             ▲<br>     +$200   │              ┌───────────────── Max Profit<br>             │             /<br>         $0  ┼────────────┼───────────────────► CRWD Price<br>             │           / $195.00<br>     -$800   │──────────┘ $185.00<br>             ▼  Breakeven: $193.00</pre><h3>5. Put Ratio Spreads (5:20–6:39)</h3><p><strong>Concept:</strong> A 1x2 strategy where you buy 1 closer OTM put and sell 2 further OTM puts, usually structured for a small net credit or zero cost.</p><ul><li><strong>CRWD Setup:</strong></li><li>Buy 1x $200 Put @ $5.00 debit</li><li>Sell 2x $185 Puts @ $3.00 credit each ($6.00 total)</li><li><strong>Net Credit Collected:</strong> <strong>$1.00</strong> ($100)</li><li><strong>Max Profit:</strong> $1,600 [($200 — $185 spread width = $15) + $1.00 Net Credit × 100] if CRWD expires right at $185.00.</li><li><strong>Max Downside Risk:</strong> Substantial below $169.00 ($185 — $16.00 max profit point).</li></ul><pre>Profit / Loss<br>             ▲           Peak Profit: $1,600 @ $185<br>   +$1,600   │               /\<br>     +$100   │──────────────/  \─────────────── Min Profit ($100)<br>         $0  ┼─────────────┼────\──────────────► CRWD Price<br>             │            / $200 \ $185<br>             │           /        \<br>             ▼ Breakeven: $169.00  Downside Risk</pre><h3>6. Short Call Spreads (6:39–8:06)</h3><p><strong>Concept:</strong> A defined-risk bear call spread created by selling a lower OTM call and buying a higher OTM call to profit from overvalued or capped upside.</p><ul><li><strong>CRWD Setup:</strong></li><li>Sell $230 Call</li><li>Buy $240 Call</li><li><strong>Net Credit Collected:</strong> <strong>$2.20</strong> ($220)</li><li><strong>Max Profit:</strong> $220.</li><li><strong>Max Loss:</strong> $780 [($240 — $230 Width) — $2.20 Credit × 100].</li><li><strong>Breakeven:</strong> $232.20.</li></ul><pre>Profit / Loss<br>             ▲<br>     +$220   │─────────────────┐ Max Profit<br>             │                  \<br>         $0  ┼───────────────────┼────────────► CRWD Price<br>             │ $230               \ $240<br>     -$780   │                     └────────── Max Loss<br>             ▼  Breakeven: $232.20</pre><h3>7. Broken Wing Butterfly (8:06–9:33)</h3><p><strong>Concept:</strong> A skip-strike butterfly (Buy 1, Sell 2, Buy 1) structured asynchronously to create a trade with zero risk on one side and a net credit upfront.</p><ul><li><strong>CRWD Setup (Put BWB):</strong></li><li>Buy 1x $210 Put</li><li>Sell 2x $200 Puts</li><li>Buy 1x $185 Put (Skipped $190 strike)</li><li><strong>Net Credit Collected:</strong> <strong>$0.75</strong> ($75)</li><li><strong>Max Profit:</strong> $1,075 [($210 — $200 upper spread width) + $0.75 Credit × 100] at $200.</li><li><strong>Upside Risk:</strong> $0 (Collect $75 credit if CRWD stays above $210).</li><li><strong>Max Downside Loss:</strong> $425 [($200 — $185 lower width = $15) — $10.75 max profit].</li></ul><pre>Profit / Loss<br>             ▲         Peak: $1,075 @ $200<br>   +$1,075   │              /\<br>     +$75    │─────────────/  \─────────────── Upside Flat Credit ($75)<br>         $0  ┼────────────┼────\──────────────► CRWD Price<br>             │           / $210 \ $200<br>     -$425   │──────────┘ $185<br>             ▼</pre><h3>8. Unbalanced Iron Condor (9:33–11:04)</h3><p><strong>Concept:</strong> A directional Iron Condor skewing risk by using a wider call spread than put spread, capturing a bearish/neutral bias while collecting higher credit.</p><ul><li><strong>CRWD Setup:</strong></li><li><em>Put Side ($10 wide):</em> Sell $195 Put / Buy $185 Put</li><li><em>Call Side ($15 wide):</em> Sell $225 Call / Buy $240 Call</li><li><strong>Total Net Credit:</strong> <strong>$4.00</strong> ($400)</li><li><strong>Max Loss (Call Side):</strong> $1,100 ($15 call width — $4.00 credit × 100).</li><li><strong>Max Loss (Put Side):</strong> $600 ($10 put width — $4.00 credit × 100).</li></ul><pre>Profit / Loss<br>             ▲<br>     +$400   │             ┌───────────┐ Max Profit<br>         $0  ┼────────────┼─────────────┼─────────► CRWD Price<br>     -$600   │───────────┘ $195       $225\<br>    -$1,100  │                             └────── Max Loss Call Side<br>             ▼</pre><h3>9. Iron Condor (11:04–12:07)</h3><p><strong>Concept:</strong> Selling a symmetrical OTM put spread and call spread to profit from rangebound price movement and IV decay.</p><ul><li><strong>CRWD Setup:</strong></li><li>Sell $195 Put / Buy $185 Put ($10 width)</li><li>Sell $230 Call / Buy $240 Call ($10 width)</li><li><strong>Total Net Credit:</strong> <strong>$3.80</strong> ($380)</li><li><strong>Max Profit:</strong> $380 (If CRWD stays between $195 and $230).</li><li><strong>Max Loss:</strong> $620 ($10.00 Width — $3.80 Credit × 100).</li><li><strong>Breakevens:</strong> $191.20 and $233.80.</li></ul><pre>Profit / Loss<br>             ▲<br>     +$380   │          ┌─────────────────┐ Max Profit<br>         $0  ┼─────────┼───────────────────┼────────► CRWD Price<br>             │        / $195             $230\<br>     -$620   │───────┘                        └───── Max Loss<br>             ▼ Breakeven: $191.20     Breakeven: $233.80</pre><h3>10. Short Strangles (12:13–13:55)</h3><p><strong>Concept:</strong> Selling an undefined-risk OTM put and OTM call outside the expected move. Top-performing strategy due to high probability of profit and double theta decay.</p><ul><li><strong>CRWD Setup:</strong></li><li>Sell $190 Put (~15 Delta) for $3.80</li><li>Sell $235 Call (~15 Delta) for $3.20</li><li><strong>Total Net Credit Collected:</strong> <strong>$7.00</strong> ($700)</li><li><strong>Max Profit:</strong> $700.</li><li><strong>Max Loss:</strong> Undefined on both sides.</li><li><strong>Breakevens:</strong> $183.00 ($190 — $7) and $242.00 ($235 + $7).</li></ul><pre>Profit / Loss<br>             ▲<br>     +$700   │               ┌───┐ Max Profit<br>         $0  ┼──────────────┼─────┼───────────► CRWD Price<br>             │             / $190  \ $235<br>             │            /         \<br>             ▼ Undefined Risk     Undefined Risk</pre><h3>11. Price Reversion &amp; Pairs Trading (13:55–15:48)</h3><p><strong>Concept:</strong> Trading relative value by exploiting statistical divergence between CRWD and a correlated asset (e.g., PANW), or betting on elevated Implied Volatility (IV) to revert to its historical mean.</p><ul><li><strong>CRWD Application:</strong></li><li><strong>Pairs Trade (CRWD vs. PANW):</strong> If the CRWD/PANW ratio expands +2 Standard Deviations above its 50-day moving average, short CRWD stock / sell CRWD calls while buying PANW stock / buying PANW calls.</li><li><strong>IV Mean Reversion:</strong> If CRWD IV Rank spikes above 70% ahead of earnings, execute short vega strategies (Strangles, Iron Condors) to profit as IV drops immediately post-announcement.</li></ul><pre>Ratio Spread / Implied Volatility<br>            ▲<br>            │     /\  CRWD Overextended (+2 Std Dev) -&gt; Sell / Short<br>            │    /  \<br>    Mean ───┼───/────\───────/────\───────────── Target Mean<br>            │  /      \     /      \<br>            │ /        \___/        \ CRWD Undervalued -&gt; Buy / Long<br>            ▼</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d39b86313f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Complete RWA Loan Lifecycle System with Merkle Proofs]]></title>
            <link>https://medium.com/@itsme24543/building-a-complete-rwa-loan-lifecycle-system-with-merkle-proofs-e7b2d4c2f285?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b2d4c2f285</guid>
            <category><![CDATA[merkle-tree]]></category>
            <category><![CDATA[loans]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[rwa]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 00:31:23 GMT</pubDate>
            <atom:updated>2026-07-05T00:31:23.644Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-World Assets (RWAs), particularly private credit loans, are inherently complex financial instruments. Bringing them on-chain presents a major architectural challenge: loan origination is data-heavy, involves sensitive Personally Identifiable Information (PII) that must never touch a public ledger, and suffers from low conversion rates where many approved loans are never ultimately claimed by borrowers.</p><p>Stating this simply: storing metadata for thousands of un-filled loans directly inside Ethereum storage slots is a gas-allocation disaster.</p><p>To build a production-grade, capital-efficient loan origination system, we must separate <strong>eligibility verification</strong> from <strong>stateful lifecycle management</strong>.</p><p>By leveraging cryptographic Merkle proofs, we can compress an entire database of approved loans into a single 32-byte tracking fingerprint on-chain, forcing the storage footprint to scale log-linearly rather than linearly.</p><h3>The Complete Loan Anatomy</h3><p>To model the lifecycle of an asset safely, we break down our loan data into an immutable verification layer and a stateful execution layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1e6GlFY5nzfGq0Pp-8bPew.png" /></figure><h3>The Gas Mitigation Strategy</h3><p>Before a borrower interacts with our contract, the entire underwriting list remains off-chain. Instead of publishing individual parameters for every approved applicant, the system administrator deploys a single 32-byte hash:</p><pre>bytes32 public loanMerkleRoot = 0xd283864358ff61ace1f39e6ccfeae76d442504f910527c254caab16020323c58;</pre><p>Writing this single root costs roughly <strong>50,000 gas</strong>, whether the underlying pool contains 10 or 1,000,000 approved loans.</p><p>When an authorized borrower decides to claim their capital, they submit their specific parameters (principal, interestRate) along with a cryptographic array of hashes (the proof). The contract evaluates the proof against the root. If valid, it instantiates the stateful tracking mapping <em>only</em> for that active borrower:</p><pre>// Storage slots are only allocated for active, claimed loans<br>mapping(address =&gt; Loan) public loans;</pre><h3>Step 1: Off-Chain Tree Generation (TypeScript)</h3><p>To ensure the smart contract can verify eligibility, the off-chain system must build a deterministic tree using merkletreejs.</p><p>A critical security vulnerability in Merkle-based distribution systems is the <strong>second-preimage attack</strong>, where an attacker manipulates leaf lengths to spoof intermediate hashes. To defend against this, we use a <strong>double-hashing strategy</strong>: we encode the data components, take the initial Keccak256 hash, and then hash the resulting slice a second time before adding it as a tree leaf.</p><pre>import { ethers } from &quot;hardhat&quot;;<br>import { MerkleTree } from &quot;merkletreejs&quot;;</pre><pre>// 1. Encode the unique loan allocation parameters<br>const encodedData = ethers.AbiCoder.defaultAbiCoder().encode(<br>  [&quot;address&quot;, &quot;uint256&quot;, &quot;uint256&quot;],<br>  [borrower.address, borrower.principal, borrower.interestRate]<br>);</pre><pre>// 2. Double-hash to immunize against length-extension/preimage attacks<br>const leaf = ethers.keccak256(<br>  ethers.concat([ethers.keccak256(encodedData)])<br>);</pre><pre>// 3. Construct the balanced tree with pair sorting enabled<br>const tree = new MerkleTree(leaves, ethers.keccak256, { sortPairs: true });<br>const root = tree.getHexRoot();</pre><pre>// 4. Extract the compact verification proof for this specific borrower<br>const proof = tree.getHexProof(leaf);</pre><h3>Step 2: The On-Chain Verification Engine (Solidity)</h3><p>Inside the smart contract layer, the incoming payload must replicate the exact deterministic leaf generation process executed by our TypeScript environment before passing it to the cryptographic verification library.</p><p>The proof size scales logarithmically:</p><p>Proof Size = log₂(n)</p><p>. While a pool of 4 loans requires only 2 hashes for validation, a massive institutional framework tracking 1,000,000 active loans requires a maximum of only 20 hashes to execute validation on-chain.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;</pre><pre>import &quot;@openzeppelin/contracts/utils/cryptography/MerkleProof.sol&quot;;<br>import &quot;@openzeppelin/contracts/token/ERC20/IERC20;</pre><pre>contract LoanPoolDemo {<br>    bytes32 public loanMerkleRoot;<br>    IERC20 public immutable usdcToken;<br>    <br>    enum LoanStatus { NotDisbursed, Active, Settled, Defaulted }</pre><pre>    struct Loan {<br>        uint256 principal;<br>        uint256 interestRate;<br>        uint256 disbursedAt;<br>        uint256 totalOwed;<br>        uint256 totalPaid;<br>        LoanStatus status;<br>    }</pre><pre>    mapping(address =&gt; Loan) public loans;</pre><pre>    event LoanClaimed(address indexed borrower, uint256 principal, uint256 totalOwed);<br>    event PaymentReceived(address indexed borrower, uint256 amountPaid, uint256 remainingOwed);</pre><pre>    constructor(address _tokenAddress) {<br>        usdcToken = IERC20(_tokenAddress);<br>    }</pre><pre>    function setMerkleRoot(bytes32 _newRoot) external {<br>        // Note: Production architectures require strict Access Control here<br>        loanMerkleRoot = _newRoot;<br>    }</pre><pre>    function claimLoan(<br>        uint256 principal, <br>        uint256 interestRate, <br>        bytes32[] calldata proof<br>    ) external {<br>        // Prevent re-initialization of already active or settled positions<br>        require(loans[msg.sender].status == LoanStatus.NotDisbursed, &quot;Loan already claimed or active&quot;);</pre><pre>        // 1. Reconstruct the leaf format using identical double-hashing logic<br>        bytes32 leaf = keccak256(<br>            bytes.concat(<br>                keccak256(abi.encode(msg.sender, principal, interestRate))<br>            )<br>        );</pre><pre>        // 2. Execute cryptographic proof validation against the immutable root<br>        bool isValid = MerkleProof.verify(proof, loanMerkleRoot, leaf);<br>        require(isValid, &quot;Cryptographic proof validation failed: Invalid loan allocation&quot;);</pre><pre>        // 3. Compute structural obligations (Example: Simple interest target generation)<br>        uint256 interestTarget = (principal * interestRate) / 10000;<br>        uint256 totalOwedTarget = principal + interestTarget;</pre><pre>        // 4. Initialize storage allocation state<br>        loans[msg.sender] = Loan({<br>            principal: principal,<br>            interestRate: interestRate,<br>            disbursedAt: block.timestamp,<br>            totalOwed: totalOwedTarget,<br>            totalPaid: 0,<br>            status: LoanStatus.Active<br>        });</pre><pre>        emit LoanClaimed(msg.sender, principal, totalOwedTarget);</pre><pre>        // 5. Transfer underlying capital to the verified borrower<br>        require(usdcToken.transfer(msg.sender, principal), &quot;Capital disbursement asset transfer failed&quot;);<br>    }<br>}</pre><blockquote><strong>The Structural Transition:</strong> Notice that once claimLoan completes verification, the internal storage slot is written. From this point forward, the <strong>smart contract</strong> completely detaches itself from the Merkle proof for this user. Future interactions bypass the root entirely and read directly from the stateful mapping.Step 3: Lifecycle Management &amp; Settlement</blockquote><p>Once a position transitions to Active, the system monitors repayments through a standard state-modifying function. The asset cannot be closed out without satisfying the precise integer obligation generated during initialization.</p><pre>function makePayment(uint256 paymentAmount) external {<br>    Loan storage loan = loans[msg.sender];<br>    require(loan.status == LoanStatus.Active, &quot;Target asset position is not currently active&quot;);<br>    require(paymentAmount &gt; 0, &quot;Repayment volume must exceed zero units&quot;);</pre><pre>    // Secure capital transfer from user to pool storage<br>    require(usdcToken.transferFrom(msg.sender, address(this), paymentAmount), &quot;Repayment ledger transfer failed&quot;);</pre><pre>    // Reconcile balances<br>    loan.totalPaid += paymentAmount;</pre><pre>    if (loan.totalPaid &gt;= loan.totalOwed) {<br>        loan.status = LoanStatus.Settled;<br>    }</pre><pre>    emit PaymentReceived(msg.sender, paymentAmount, loan.totalOwed - loan.totalPaid);<br>}</pre><h3>Architectural Protections Provided by the Engine</h3><p>By forcing the execution environment to trace this cryptographic hierarchy, the system automatically gains built-in protections against common smart contract attack vectors:</p><ul><li><strong>Identity Spoofing Immunity:</strong> If a malicious third party steals a legitimate borrower’s proof array and tries to claim it, the call fails. The contract utilizes msg.sender as a hardcoded component of the leaf reconstruction. A mismatched execution sender will produce an invalid leaf, breaking validation.</li><li><strong>Parameter Tampering Prevention:</strong> If a borrower modifies their principal down to zero or changes their interestRate to a fractional value inside their execution arguments while attaching their original proof, the reconstructed leaf will shift completely, causing a root mismatch rejection.</li><li><strong>Zero Wasted Overhead:</strong> Unclaimed allocations consume zero space within the state tree of the virtual machine. The pool manager only accounts for capital moving actively across the perimeter.</li></ul><h3>Source Code &amp; Sandbox</h3><p>If you want to run this architecture locally and see the cryptographic proofs in action, you can explore the complete repository here:</p><p>🔗 <a href="https://github.com/arnabmitra/loan-pool-eth">https://github.com/arnabmitra/loan-pool-eth</a></p><p><strong>What this repository does:</strong> It serves as a complete, step-by-step sandbox for learning and implementing Merkle-based distribution systems from scratch. The repository includes:</p><ul><li><strong>Off-chain Logic:</strong> TypeScript scripts that generate the Merkle trees and simulate users building their cryptographic leaves.</li><li><strong>On-chain Logic:</strong> The Solidity smart contracts (including the foundational MerkleProofDemo and the fully stateful LoanPoolDemo implementation).</li><li><strong>Testing Environment:</strong> A fully integrated Hardhat environment that demonstrates how to securely process claims, prevent double-spending, and execute lifecycle state transitions.</li></ul><p>Structuring real-world debt systems requires balancing trustless validation with the economic constraints of blockchain environments. By utilizing Merkle trees to anchor data off-chain while selectively populating stateful tracking contracts upon user interaction, we completely isolate our smart contracts from bloated tracking arrays.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b2d4c2f285" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High-Performance Order Matching Engine in Go: Demystifying the container/heap]]></title>
            <link>https://medium.com/@itsme24543/building-a-high-performance-order-matching-engine-in-go-demystifying-the-container-heap-bebc79780c65?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebc79780c65</guid>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[matching]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 00:20:27 GMT</pubDate>
            <atom:updated>2026-07-04T00:20:27.603Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a comprehensive, principal-level Medium article draft based exactly on our architectural teardowns and Go implementations. It is formatted for Medium with clear headings, code blocks, and architectural explanations.</p><h3>Building a High-Performance Order Matching Engine in Go: Demystifying the container/heap</h3><p>If you are building a crypto exchange, routing options flow, or designing a high-throughput trading system, the heartbeat of your architecture is the <strong>Limit Order Book</strong>.</p><p>At its core, a matching engine is a ruthless priority system. When a buyer wants shares, they want the absolute cheapest price available. When a seller offers shares, they want the highest paying buyer. In both cases, if two people offer the exact same price, the person who placed their order first wins. This is known as <strong>Price-Time Priority</strong>.</p><p>To execute this deterministically at scale, we don’t use standard arrays or relational databases. We use a <strong>Priority Queue</strong>, specifically implemented via a Binary Heap.</p><p>In this article, we are going to build a high-performance matching engine in Go. We will bypass the common floating-point traps, decode Go’s notoriously confusing container/heap package, and build a memory-safe execution loop.</p><h3>The Architecture: Bids, Asks, and Heaps</h3><p>An Order Book consists of two opposing sides:</p><ul><li><strong>The Bids (Buyers):</strong> We want the highest price to execute first. This requires a <strong>Max-Heap</strong>.</li><li><strong>The Asks (Sellers):</strong> We want the lowest price to execute first. This requires a <strong>Min-Heap</strong>.</li></ul><p>When a new market order comes in, it attempts to consume liquidity from the opposing heap until it is completely filled or the price is no longer favorable.</p><h3>Trap 1: The Floating-Point Disaster</h3><p>Before writing a single line of queue logic, we must define our Order structure. The most common mistake engineers make here is using float64 or a heavy BigDecimal library for the price.</p><p>In high-frequency systems, BigDecimal triggers massive garbage collection (GC) spikes due to heap allocations, and float64 introduces IEEE 754 rounding errors that will inevitably corrupt your ledger.</p><p>The industry standard is <strong>Fixed-Point Integer Math</strong>. We store prices as 64-bit integers (int64) representing the smallest fractional unit (like pennies or Satoshis). This allows the CPU to use native, zero-allocation integer arithmetic.</p><pre>type Order struct {<br>	ID        string<br>	IsBuy     bool<br>	Price     int64 // Scaled integer (e.g., $150.25 -&gt; 15025)<br>	Size      int<br>	Timestamp int64 // Used for FIFO tie-breaking<br>}</pre><h3>The Go container/heap: Orchestrator vs. Worker</h3><p>Go’s standard library provides a container/heap package, but it is deeply misunderstood. Instead of providing an out-of-the-box Queue object, Go provides an <strong>Orchestrator</strong>.</p><p>The Orchestrator contains complex binary tree math that allows it to treat a flat 1D slice as a perfectly balanced Complete Binary Tree.</p><p>To use the Orchestrator, you must provide the <strong>Workers</strong> — a specific set of interface methods (Len, Less, Swap, Push, Pop) attached to your slice.</p><p>Let’s implement the AskQueue (Sellers), which must act as a Min-Heap.</p><pre>type AskQueue []*Order</pre><pre>func (aq AskQueue) Len() int { return len(aq) }</pre><pre>func (aq AskQueue) Swap(i, j int) { aq[i], aq[j] = aq[j], aq[i] }</pre><pre>// The Less method defines our Price-Time Priority<br>func (aq AskQueue) Less(i, j int) bool {<br>	// 1. Price Priority: Lowest price floats to the top<br>	if aq[i].Price != aq[j].Price {<br>		return aq[i].Price &lt; aq[j].Price<br>	}<br>	// 2. Time Priority: If prices match, oldest timestamp wins<br>	return aq[i].Timestamp &lt; aq[j].Timestamp<br>}</pre><h3>Trap 2: The Memory Leak in Pop</h3><p>If you come from Java or Kotlin, writing your own Pop() method for a standard library data structure feels backward. Why doesn&#39;t Go just slice the array for you?</p><p>The answer lies in garbage collection. Because our heap holds pointers ([]*Order), simply shrinking the slice length isn&#39;t enough.</p><pre>func (aq *AskQueue) Push(x any) {<br>	*aq = append(*aq, x.(*Order))<br>}</pre><pre>func (aq *AskQueue) Pop() any {<br>	old := *aq<br>	n := len(old)<br>	item := old[n-1]<br>	<br>	old[n-1] = nil // CRITICAL: Prevent memory leaks<br>	<br>	*aq = old[0 : n-1]<br>	return item<br>}</pre><p>If we omitted old[n-1] = nil, the underlying array capacity would still hold a reference to that memory address, preventing the GC from ever reclaiming the executed order. Go forces you to write Pop so you can explicitly handle pointer cleanup.</p><blockquote><strong><em>The “Index n-1” Optical Illusion:</em></strong><em>n-1 Notice that our </em><em>Pop method returns the </em>last<em> element (</em><em>n-1), not the best price at index </em><em>0. This is because Go&#39;s Orchestrator (</em><em>heap.Pop) swaps the winning root element to the end of the array </em>before<em> calling your custom method!</em></blockquote><h3>The Execution Engine</h3><p>With our Min-Heap perfectly tuned, we can write the execution loop.</p><p>When an incoming buy order hits the engine, we peek at the top of the AskQueue. If the price is agreeable, we calculate the trade size and deduct the shares. We must be exceptionally careful to use the min available size to avoid creating negative share balances during partial fills.</p><pre>import &quot;container/heap&quot;</pre><pre>func min(a, b int) int {<br>	if a &lt; b {<br>		return a<br>	}<br>	return b<br>}</pre><pre>func MatchBuyOrder(buy *Order, asks *AskQueue) {<br>	// Keep matching while the buyer wants shares AND sellers exist<br>	for buy.Size &gt; 0 &amp;&amp; asks.Len() &gt; 0 {<br>		<br>		bestAsk := (*asks)[0] // Peek at the absolute best price</pre><pre>		// If the cheapest seller wants more than we will pay, halt execution.<br>		if bestAsk.Price &gt; buy.Price {<br>			break<br>		}</pre><pre>		// Calculate partial or full fill volume<br>		tradeSize := min(buy.Size, bestAsk.Size)<br>		<br>		// Deduct liquidity<br>		buy.Size -= tradeSize<br>		bestAsk.Size -= tradeSize</pre><pre>		// If the resting seller is completely tapped out, remove them from the heap<br>		if bestAsk.Size == 0 {<br>			heap.Pop(asks) <br>		}<br>	}<br>}</pre><h3>Conclusion</h3><p>Building a matching engine exposes the reality of systems programming: the abstraction layers are stripped away. You can no longer rely on BigDecimal safety nets or black-box data structures.</p><p>By flattening a binary tree into a contiguous slice, managing our own pointer cleanup, and strictly utilizing fixed-point integer arithmetic, we achieve a highly deterministic, zero-allocation execution loop capable of handling massive market volatility.</p><p>In Go, the magic isn’t in the standard library doing the work for you; the magic is in how the standard library gives you the exact tools to do the work perfectly yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebc79780c65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency, Parallelism, and Async-The Difference That Actually Matters]]></title>
            <link>https://medium.com/@itsme24543/concurrency-parallelism-and-async-the-difference-that-actually-matters-2224813b7145?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/2224813b7145</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[parallelism]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 01:58:53 GMT</pubDate>
            <atom:updated>2026-04-13T02:03:52.587Z</atom:updated>
            <content:encoded><![CDATA[<p>These terms get thrown around interchangeably. Getting them right — with Go as your guide — will make you a sharper systems thinker and a better engineer.</p><p>Go is famous for making concurrent code feel natural. But <em>why</em>? Because Rob Pike and the Go team designed it around one simple idea: <strong>concurrency is not parallelism</strong>. Understanding that distinction unlocks everything from goroutine design to GOMAXPROCS tuning.Concept,Definition,Analogy<br>Concurrency,Composing independent tasks.,&quot;One chef, three dishes in motion.&quot;<br>Parallelism,Executing tasks simultaneously.,Three chefs cooking at once.<br>Async (Channels),Non-blocking execution.,Don’t wait; be notified when ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*2teRA4bQKUmoWkcSPorvIA.png" /></figure><h3>Concurrency: Juggling Without Dropping</h3><p>Concurrency is a <strong>design concept</strong> — structuring your program so multiple tasks make progress without one blocking another. In Go, the primitive is the goroutine: a lightweight, cooperatively-scheduled green thread managed entirely by the Go runtime.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;sync&quot;<br>    &quot;time&quot;<br>)<br><br>func worker(id int, wg *sync.WaitGroup) {<br>    defer wg.Done()<br>    fmt.Printf(&quot;Worker %d starting\n&quot;, id)<br>    time.Sleep(500 * time.Millisecond)<br>    fmt.Printf(&quot;Worker %d done\n&quot;, id)<br>}<br><br>func main() {<br>    var wg sync.WaitGroup<br><br>    for i := 1; i &lt;= 5; i++ {<br>        wg.Add(1)<br>        go worker(i, &amp;wg)<br>    }<br><br>    wg.Wait()<br>    fmt.Println(&quot;All workers done&quot;)<br>}</pre><h3>Parallelism: Multiple Cores, Real Simultaneity</h3><p>Parallelism means tasks are literally executing at the same instant on different CPU cores. In Go, GOMAXPROCS controls how many OS threads run goroutines simultaneously.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;runtime&quot;<br> &quot;sync&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> cores := runtime.NumCPU()<br> runtime.GOMAXPROCS(cores)<br> fmt.Printf(&quot;The number of cores is %d \n&quot;, cores)<br><br> data := make([]int, 100_000_001)<br> for i := range data {<br>  data[i] = i + 1<br> }<br> // create chunks<br> chunkSize := len(data) / cores<br> chunks := make([][]int, 0, cores)<br><br> for i := 0; i &lt; len(data); i += chunkSize {<br>  end := i + chunkSize<br>  if end &gt; len(data) {<br>   end = len(data)<br>  }<br>  chunks = append(chunks, data[i:end])<br> }<br><br> start := time.Now()<br><br> //aggregate chunks in results<br> var wg sync.WaitGroup<br> results := make([]int, len(data))<br> for i, chunk := range chunks {<br>  wg.Add(1)<br>  go func(i int, chunk []int) {<br>   defer wg.Done()<br>   for j, val := range chunk {<br>    res, err := crunchNumbers(val)<br>    if err != nil {<br>     fmt.Printf(&quot;Error processing value %d: %v\n&quot;, val, err)<br>     continue<br>    }<br>    results[i*chunkSize+j] = res<br>   }<br>  }(i, chunk)<br> }<br> wg.Wait()<br><br> fmt.Printf(&quot;Finished processing %d numbers in %v\n&quot;, len(data), time.Since(start))<br> fmt.Printf(&quot;First 10 results: %v\n&quot;, results[:10])<br> fmt.Printf(&quot;Last 5 results: %v\n&quot;, results[len(results)-5:])<br><br>}<br><br>func crunchNumbers(n int) (int, error) {<br> return n * n, nil<br>}</pre><h3>Channels: Go’s Async Primitive</h3><p>Other languages use async/await. Go uses goroutines plus channels. Instead of promise chains, goroutines send typed results through channels.</p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;net/http&quot;<br>    &quot;sync&quot;<br>)<br><br>type Result struct {<br>    URL    string<br>    Status int<br>    Err    error<br>}<br><br>func fetch(url string, ch chan&lt;- Result, wg *sync.WaitGroup) {<br>    defer wg.Done()<br>    resp, err := http.Get(url)<br>    if err != nil {<br>        ch &lt;- Result{URL: url, Err: err}<br>        return<br>    }<br>    defer resp.Body.Close()<br>    ch &lt;- Result{URL: url, Status: resp.StatusCode}<br>}<br><br>func main() {<br>    urls := []string{<br>        &quot;https://go.dev&quot;,<br>        &quot;https://pkg.go.dev&quot;,<br>        &quot;https://github.com&quot;,<br>    }<br><br>    ch := make(chan Result, len(urls))<br>    var wg sync.WaitGroup<br><br>    for _, url := range urls {<br>        wg.Add(1)<br>        go fetch(url, ch, &amp;wg)<br>    }<br><br>    go func() {<br>        wg.Wait()<br>        close(ch)<br>    }()<br><br>    for r := range ch {<br>        fmt.Println(r.URL, r.Status, r.Err)<br>    }<br>}</pre><h3>How They All Fit Together</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*MgdEuTYCJPvXOLqtofg8-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*n3Szw7_Q8MqzOgXWzwOX9A.png" /></figure><h3>The Rob Pike Principle</h3><p>Rob Pike said it best: “Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.” Concurrency is a design concern. Parallelism is a runtime concern.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPAAkCSZUG1c%3Fstart%3D222%26feature%3Doembed%26start%3D222&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPAAkCSZUG1c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPAAkCSZUG1c%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ebd3f0ff37d689d82ff5b1ca4999986/href">https://medium.com/media/4ebd3f0ff37d689d82ff5b1ca4999986/href</a></iframe><p><a href="https://go-proverbs.github.io/">https://go-proverbs.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2224813b7145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing Nginx on a Mac and configure it to use https using self signed certificates]]></title>
            <link>https://medium.com/@itsme24543/installing-nginx-on-a-mac-and-configure-it-to-use-https-using-self-signed-certificates-b81a862ba6f0?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81a862ba6f0</guid>
            <category><![CDATA[self-signed-certificate]]></category>
            <category><![CDATA[sslsecurity]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 01:02:18 GMT</pubDate>
            <atom:updated>2024-10-27T01:02:18.193Z</atom:updated>
            <content:encoded><![CDATA[<p>I have seen many articles about nginx and how to configure it but didn’t see any where it told you how to use it with ssl and self signed certs, here is my attempt to guide you through it.</p><p>Install nginx using brew</p><pre> # Install nginx with brew<br> brew install nginx<br> # Run sudo nginx to start nginx on port 8080<br> sudo nginx<br> # Open a web browser and go to http://localhost:8080<br> # Run sudo nginx -s stop to stop nginx <br> nginx -s stop<br>You can also configure nginx to run as an unprivileged system user. To do this, you can create a new user without sudo privileges</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sfk1ojhryJYD8j0OCrUyVA.png" /></figure><p>if your nginx is running as expected you will see a page like above.</p><h3>Use Case i want to implement</h3><p>I have a server running on port 18080</p><p>I want to use nginx so that i can talk to it via a custom domain of testwebsite.com.</p><p>Remember i am only doing this locally, this does not involve me buying the domain or pointing DNS records etc.</p><p>First step is to add this to your /etc/hosts</p><pre>127.0.0.1 testwebsite.com</pre><p>add the following lines to your nginx.conf(located at /opt/homebrew/etc/nginx/nginx.conf)</p><pre>server {<br>    listen 443 ssl;<br>    listen [::]:443 ssl;<br>    server_name testwebsite.com www.testwebsite.com;<br><br>    ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;<br>    ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;<br><br>    access_log /usr/local/var/log/nginx/access.log;<br>    error_log /usr/local/var/log/nginx/error.log;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:18080;<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &quot;upgrade&quot;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>        # proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}<br><br>    include servers/*;<br>}</pre><p>Now let us make sure ssl can use our self signed certificate</p><pre>1. **Generate a New Private Key**:<br>    <br>    ```<br>    openssl genpkey -algorithm RSA -out /etc/ssl/private/nginx-selfsigned.key<br>    <br>    ```<br>    <br>2. **Create a New Certificate Signing Request (CSR) with a Valid Common Name and SAN**:<br>Create a configuration file `san.cnf` with the following content:<br>    <br>    ```<br>    [req]<br>    default_bits       = 2048<br>    distinguished_name = req_distinguished_name<br>    req_extensions     = req_ext<br>    x509_extensions    = v3_req<br>    prompt             = no<br>    <br>    [req_distinguished_name]<br>    C  = US<br>    ST = UT<br>    L  = SLC<br>    O  = ACME Corp<br>    CN = testwebsite.com<br>    <br>    [req_ext]<br>    subjectAltName = @alt_names<br>    <br>    [v3_req]<br>    subjectAltName = @alt_names<br>    <br>    [alt_names]<br>    DNS.1 = testwebsite.com<br>    DNS.2 = www.testwebsite.com<br>    <br>    ```<br>    <br>    Then, generate the CSR:<br>    <br>    ```<br>    openssl req -new -key /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.csr -config san.cnf<br>    <br>    ```<br>    <br>3. **Generate a New Self-Signed Certificate**:<br>    <br>    ```<br>    openssl x509 -req -days 365 -in /etc/ssl/certs/nginx-selfsigned.csr -signkey /etc/ssl/private/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt -extensions v3_req -extfile san.cnf<br>    <br>    ```<br>4. make sure your nginx.conf is updated as shown above<br>    <br>5. **Reload `nginx`**:<br>    <br>    ```<br>    sudo nginx -s reload<br>    <br>    ```<br><br>You can also test your config is correct by running <br>```<br> sudo nginx -t<br>```<br></pre><p>Now goto</p><p><a href="https://testwebsite.com/webauthn/register">https://testwebsite.com/&lt;</a>yourpath&gt;</p><p>you will get an SSL error on chrome</p><p>export the certificate from chrome</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*80UkOSopiAcRo2LSuStwxg.png" /></figure><p>And now add it to your mac os keychain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hAXXxizWBVNCGq7wZ0WKQ.png" /></figure><p>make sure you trust it all the time (make sure to remove it after your tests are complete!)</p><p>and restart chrome and you should be able to goto <a href="https://testwebsite.com/webauthn/register">https://testwebsite.com/&lt;</a>yourpath&gt; and hit the server you have running locally without ssl issues.</p><p>I used above to test webauthn credentials for a certain domain that i can register to the webauthn server. seems like a handy thing to do before going to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81a862ba6f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flash loans — eip-3156]]></title>
            <link>https://medium.com/@itsme24543/flash-loans-eip-3156-f175a4ae405d?source=rss-1f2c8ca41f52------2</link>
            <guid isPermaLink="false">https://medium.com/p/f175a4ae405d</guid>
            <category><![CDATA[eip-3156]]></category>
            <category><![CDATA[flashloantutorial]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[foobarbaz]]></dc:creator>
            <pubDate>Sun, 25 Feb 2024 19:19:35 GMT</pubDate>
            <atom:updated>2024-02-25T19:19:35.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Flash loans — <a href="https://eips.ethereum.org/EIPS/eip-3156">eip-3156</a></h3><h3>Motivation</h3><p>Flash loans allow smart contracts to lend an amount of tokens without a requirement for collateral, with the condition that they must be returned within the same transaction.</p><p>All this below is happening in one transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRDiDmuVvlBIjwIeSAkTOA.png" /></figure><p>If funds are not returned all transaction are reversed.</p><p>All of this is done via smart contracts, there are two main smart contracts in play(there can be multiple intermediary smart contract) but mainly there is lending smart contract (like what aave provides) and the invokers smart contract (the person taking the loan to do something)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xI3uohN4giFvMOg5kk023A.png" /></figure><p>Aave, balancer, uniswap etc provide contracts for such lending</p><p>Here are the aave docs</p><p><a href="https://docs.aave.com/developers/guides/flash-loans">https://docs.aave.com/developers/guides/flash-loans</a></p><p>Balancer has same docs</p><p><a href="https://docs.balancer.fi/reference/contracts/flash-loans.html">https://docs.balancer.fi/reference/contracts/flash-loans.html</a></p><p>a template for flash loans on uniswap:</p><p><a href="https://github.com/jtriley-eth/uni-v4-core-flashloans#readme">https://github.com/jtriley-eth/uni-v4-core-flashloans#readme</a></p><h3>What are flashloans used for?</h3><p><strong>Arbitrage</strong></p><p>The most common use case for a flash loan is to do an arbitrage trade. For example, if Ether is trading for $1,200 in one pool and $1,300 in another DeFi application, it would be desirable to buy the Ether in the first pool and sell it in the second pool for a $100 profit. However, you need to money to buy the Ether in the first place. A flash loan is the ideal solution for it, as you don’t need $1,200 lying around. You can borrow $1,200 of Ether, sell it for $1,300, and pay back the $1,200 keeping a $100 profit for yourself (minus fees).</p><p><strong>Refinancing Loans</strong></p><p>For regular DeFi loans, they typically require some kind of collateral. For example, if you were borrowing $10,000 in stable coins, you would need to deposit $15,000 of Ether as collateral.</p><p>If your stable coins loan had a 5% interest and you wanted to refinance with another lending smart contract at 4%, you would need to</p><ol><li>pay back the $10,000 in stable coins</li><li>withdraw the $15,000 Ether collateral</li><li>deposit the $15,000 Ether collateral into the other protocol</li><li>borrow $10,000 in stable coins again at the lower rate</li></ol><p>This would be problematic if you had the $10,000 tied up in some other application. With a flashloan, you can do steps 1–4 without using any of your own stable coins.</p><p><strong>Exchanging collateral</strong></p><p>In the example above, the borrower was using $15,000 of Ether as collateral. But suppose the protocol is offering a lower collateralization ratio using wBTC (wrapped bitcoin)? The borrower could use a flash loan and a similar set of steps outline above to swap out the collateral instead of the principal.</p><p><strong>Liquidating Borrowers</strong></p><p>In the context of DeFi loans, if the collateral falls below a certain threshold, then the collateral can get liquidated — forcibly sold to cover the cost of the loan. In the example above, if the value of the Ether was to drop to $12,000, then the protocol might allow someone to purchase the Ether for $11,500 if they first pay back the $10,000 loan.</p><p>A liquidator could use a flash loan to pay off the $10,000 stable coin loan and receive $11,500. They would then sell this on another exchange for stable coins, and then pay back the flash loan.</p><p><strong>Increase yield for other DeFi applications</strong></p><p>Uniswap and AAVE earn depositors’ money through trading fees or lending interest. But since they have such a large amount of capital in one place, they can make additional money by also offering flash loans. This increases the efficiency of capital since the same capital now has more uses.</p><p><strong>Hacking Smart Contracts</strong></p><p>Flash loans are probably most famous for their use by black hat hackers to exploit protocols. The primary attack vectors for flash loans are price manipulation and governance (vote) manipulation. Used on DeFi applications with inadequate defense, flash loans allow attackers to heavily buy up an asset increasing its price, or acquiring a bunch of voting tokens to push through a governance proposal.</p><p>The following is a list of flash loan hacks for the curious. Vulnerability is two-sided however. A flash lending and flash borrowing contract can also be vulnerable to losing money if not implemented properly.</p><p>Usually Flash loan providers charge fees, this is how they benefit</p><h3>Aave Flash Loan Fees</h3><p>The flash loan fee on Aave is initially set at 0.05% at the time of deployment and can be updated via a Governance Vote. The current value can be obtained using the FLASHLOAN_PREMIUM_TOTAL.</p><p>The flash loan fee is split between the liquidity providers (LPs) and the protocol treasury. The FLASHLOAN_PREMIUM_TOTAL represents the total fee paid by the borrowers, which is divided as follows:</p><ul><li>Fee to Liquidity Providers (LPs): FLASHLOAN_PREMIUM_TOTAL - FLASHLOAN_PREMIUM_TO_PROTOCOL</li><li>Fee to Protocol: FLASHLOAN_PREMIUM_TO_PROTOCOL</li></ul><h3>EIP for standardizing Flash Loans</h3><p>Read more here <a href="https://eips.ethereum.org/EIPS/eip-3156">https://eips.ethereum.org/EIPS/eip-3156</a></p><h3>Example of flash loan</h3><p><a href="https://etherscan.io/tx/0x6e808425bffd8aa53c9cb190251907d494fc6883ea32062d9cc80434a0b1cd84">https://etherscan.io/tx/0x6e808425bffd8aa53c9cb190251907d494fc6883ea32062d9cc80434a0b1cd84</a></p><ol><li><strong>Aave Liquidation:</strong> Based on the “Liquidation” action, this flash loan was likely triggered as part of liquidating an undercollateralized position on the Aave platform. Here’s how it breaks down:</li></ol><ul><li><strong>Collateral:</strong> The liquidated position had 738.910295090315204187 MANA as collateral.</li><li><strong>Debt:</strong> 0.385664245699518349 MKR repaid here.</li></ul><ol><li><strong>Flash Loan for Profitable Liquidation:</strong> The flash loan contract takes out a temporary loan of 0.385664245699518349 MKR from Aave.</li><li><strong>Repay the Debt:</strong> The contract uses the borrowed MKR to settle the outstanding debt on the liquidated position in Aave. This frees up the MANA collateral.</li><li><strong>MANA to ETH:</strong> The flash loan contract swaps the 738.910295090315204187 MANA (freed collateral) for 0.354694523616214579 ETH on Uniswap V3.</li><li><strong>ETH to MKR:</strong> The ETH, likely with some added for profit, is used to buy back 0.385664245699518349 MKR on Uniswap V3.</li><li><strong>Flash Loan Repayment:</strong> The flash loan contract repays the borrowed MKR to Aave, along with any associated fee.</li></ol><p>Finally flash loan invoker makes some ETH</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_2cM-955OqJFF1Nic4a2A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f175a4ae405d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>