<?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 Mark Richardson on Medium]]></title>
        <description><![CDATA[Stories by Mark Richardson on Medium]]></description>
        <link>https://medium.com/@mark.richardson87?source=rss-dc6f0052b77e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g9jWApggF_Jj61oqXxkXJw.jpeg</url>
            <title>Stories by Mark Richardson on Medium</title>
            <link>https://medium.com/@mark.richardson87?source=rss-dc6f0052b77e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:10:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mark.richardson87/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 Case for Constructive Adversarialism at Mainstream Conferences]]></title>
            <link>https://blog.bancor.network/the-case-for-constructive-adversarialism-at-mainstream-conferences-db401cf6a652?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/db401cf6a652</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[token-engineering]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[tech-conference]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 15:20:57 GMT</pubDate>
            <atom:updated>2026-01-21T15:43:10.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AWl216May3sXzKH_c0RIg.png" /></figure><p>The contemporary blockchain conference circuit has increasingly adopted the structure of an industrial trade show. This evolution is neither accidental nor without merit. The “expo” format efficiently concentrates builders, vendors, users, and investors in a single venue, enabling hiring, partnerships, product education, and commercial coordination at scale. These functions are legitimate, and in many cases essential. I do not approach this reality with disdain; in my role as Project Lead at Bancor, I am directly reliant on the connective utility that such events provide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-yyo4xySZdT75JA3d2qQoQ.png" /></figure><p>The concern, however, is not that conferences serve commercial ends, but that commercial optimization has become their dominant (often exclusive) organizing principle. As flagship events have oriented themselves primarily around user acquisition and business development, less space has remained for the forms of intellectual work that originally gave this field its coherence: careful problem formulation, explicit assumptions, technical disagreement, and disciplined critique. The result is not a failure of convening, but a narrowing of what is permitted to matter within the convening itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nk5pRjbjfAwLCqYPLWpoWg.png" /></figure><p>This shift has had consequences. In earlier phases of the industry, ideas were expected to withstand interrogation. Claims were refined through argument. Models were debated publicly, and disagreement was treated as productive rather than impolite. In more mature scientific and engineering disciplines, such practices are formalized through seminars, peer review, and editorial norms. Within blockchain, by contrast, they are often displaced by narrative incentives that reward consistency of message over accuracy, and optimism over examination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evj0K3RQFxDpetR0JiZwJQ.png" /></figure><p>The cumulative effect is subtle but corrosive. Simplified talking points crowd out technical explanation, metrics circulate without definition, and assertions are repeated without models. Disagreements are softened into “community” language rather than resolved through analysis. Over time, serious researchers and practitioners disengage, not in protest, but in recognition that the available forums no longer reward the work they are trained to do. What remains is discourse optimized for repetition rather than understanding. It is against this backdrop that efforts to reintroduce structured, research-first forums matter; not as alternatives to conferences, but as correctives within them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QM-gZuXkVblekVtaveFEfA.png" /></figure><p>It is a profound relief to see the <strong>Token Engineering Academy (TE Academy)</strong> take the initiative to create a forum where the only cost of entry is intellectual discipline: concise exposition, clear problem statements, methods, results, and limitations, with marketing content treated as a category error rather than tolerated background noise. I am proud that <strong>Bancor</strong> is actively collaborating in the execution of this new, strictly academic forum, the <strong>TE Research Symposium (TERSE)</strong>, premiering at <strong>EthCC[9] 2026</strong> in Cannes. I am equally proud to serve on the steering committee that is pushing to make this a real symposium, not a renamed track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctsV50d-6XCXC2rbWXYDxw.png" /></figure><p>I do not write this as a casual observer of the TE Academy ecosystem, nor as a one-time contributor stepping forward because an event now exists that flatters my preferences. Throughout my tenure as Project Lead at Bancor, I have deliberately utilized public technical forums as a corrective instrument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AjGMYueAGkpnTO4TgqTk3g.png" /></figure><p>My involvement with the TE Academy began in March 2021, during the “<a href="https://youtube.com/playlist?list=PL-GxJch-YeZct7eh35dYN7QYygPa5VbER&amp;si=93fwu6DSHCv_PELJ">Balancer Simulations</a>” program. At that time, I presented a high-level overview of the utility of elastic-supply tokens as well as a use case for AMMs in trading insurance-linked securities (ILS), a notable and early foreshadowing of the current discourse on Real-World Assets (RWAs). In July 2023, during the TE Academy track of <a href="https://www.youtube.com/live/__KmI63qwgU?si=QB40jma6pCse7aZ1">EthCC[6]</a> in Paris, I spoke about Carbon Defi (Bancor’s flagship exchange product) for the first time in front of a live audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_RjuU5hHGyElW1Y4o_ehA.png" /></figure><p>While still servicing the need to introduce, then, a relatively new concept in onchain exchange primitives, the talk was nonetheless a technical account of the product design and its mathematical structure. That technical correctness and pedagogical objectives should take priority over a cheap opportunity to shill a product has largely characterized all public seminars I have delivered for Carbon DeFi, with and without the TE Academy, as evidenced by my work at <a href="https://youtu.be/YL3XVhRGHhk?si=yhGhuLGYZ1uK8Qz8">ETHWarsaw[3]</a> and <a href="https://youtu.be/EAqJasNTjyA?si=YJ1sPWUVi-aaSSs-">ETHWarsaw[4]</a> (September, 2024 and 2025), <a href="https://youtu.be/NTDhN6cDq38?si=jcqwRLvnjLifNN1A">Devconnect</a> (November, 2025), <a href="https://youtu.be/v45Zu50ZUIc?si=C7h2_2nTC8yVAYK7">ETHDubai</a> (April, 2024), and <a href="https://youtu.be/2Mh7qPm9I18?si=Pif9VqS2UA7LhIBP">NapulETH</a> (September, 2024). This emphasis also extends to my written contributions. Even in my relatively infrequent posts on this blog, my treatment of Carbon DeFi is predominantly technical and centered on implementational details rather than narrative positioning. A representative example is “<a href="https://medium.com/carbondefi/theory-vs-reality-e4c40625767f">Theory vs Reality: The Precision and Accuracy of Carbon DeFi’s Fixed-Point Arithmetic</a>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADYUYqUw9dKAH6JdPBE4jA.png" /></figure><p>In July 2024, during the TE Academy track of <a href="https://youtu.be/fUTf0hSxrg8?si=oFJBpICdzr7flB1Q">EthCC[7]</a> in Brussels, I presented “Fixing Objectively Bad Models in LP Performance Evaluations”. This talk was not product-oriented; it was a critique of prevailing industry practices, including a specific argument that the term “fees”, as commonly used in AMM performance narratives, fails as a coherent analytical object and should be discarded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cBfHnijUUBpx7qXCjOephA.png" /></figure><p>I have maintained such non-product, industry-first objectives outside of TE Academy programming and with explicit claims that can be scrutinized, falsified, and improved. In October 2024, I presented a technical treatment of DEX MEV at <a href="https://www.linkedin.com/posts/bancor-foundation_at-mev-shanghai-bancor-project-lead-dr-activity-7250769774308175872-BTfF?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAAAKDlYwBmyHswTQ7jn3astNkQiksCwyC0cc">MEVShanghai</a>. This talk was later refined for <a href="https://youtu.be/KvffUfH0o0Y?si=OW8XBg0BDGAHrtWi">ETHDubai</a> (April 2025), separating sandwich attacks from arbitrage and insisting on precise claims about who bears which costs, and under what assumptions. In June 2025, I delivered a sandwich-attack-focused version at <a href="https://youtu.be/WhOsbsjfrbM?si=Dsz_YOJ_RUeVdOmg">ETHBelgrade</a>, and an even more thorough version for the <a href="https://www.linkedin.com/posts/uzh-blockchain-center_mev-dex-blockchain-activity-7404504072508153856-eYC0?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAAAKDlYwBmyHswTQ7jn3astNkQiksCwyC0cc">University of Zurich Blockchain Center</a> in December 2025. Related treatments also appear in my written work, including “<a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">The Optimum Sandwich: How to Exploit Blockchain Enthusiasts with Arbitrary Precision</a>” and “<a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98">The Forbidden Sandwich: A Theory of MEV-resistant CFMM Transactions</a>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Erph7YhLd0lwZjWOgOBDAQ.png" /></figure><p>In April 2025, during the TE Academy track of <a href="https://youtu.be/laWDF6gNESc?si=pG-YdnXJhc5E1I2-">EthCC[8]</a> in Cannes, I assumed the role of a critical interlocutor, chairing the “TE Unplugged” session. Rather than providing the customary “soft validation” common at crypto events, my role was to provide a form of real-time, public peer review for speakers Vasily Sumanov (Valueverse.ai) and Phillip Zahn (20squares) after their talks. This “agreeably disagreeable” posture, grounded in open criticism, is exactly what TERSE seeks to revive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FAnQUX_pg6AGeJltL5_4Q.png" /></figure><p>In October 2023, I delivered a four-part lecture series for the <a href="https://youtube.com/playlist?list=PLDaP0KzysYhj2ykLV1KYXRrI7CpSZgaMe&amp;si=SBU6AZNhs0tP6OZO">Bonding Curve Research Group</a>, which served as the progenitor for a five-part postgraduate-level lecture series “<a href="https://youtube.com/playlist?list=PL-GxJch-YeZdovBEsRBbfn6vPQwrJ4NV2&amp;si=lUqljtVMm9qPvIcZ">DeFi’s Concentrated Liquidity From Scratch</a>” (and an accompanying <a href="https://arxiv.org/abs/2407.02496">85-page textbook</a>) for the <a href="https://www.youtube.com/live/D6q5U-zb5jk?si=sWuHjR6gT5oWZgRG">TE Academy Study Season</a> (April-July 2024).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D4qw_9XUdA2ttruIfaXf9A.png" /></figure><p>This record is the reason I am willing to speak plainly. My relationship with the TE Academy provides provenance earned through a consistent body of technical work across multiple years and formats, from foundational lecture series and published course material to public critical inquiry. It has allowed me to inhabit a role that is too often absent from the conference circuit, which treats discourse as an arena for interrogation rather than a venue for marketing theater.</p><p>In my view, TERSE is the formalization of this posture. It is a concerted effort to restore a durable bridge between theoretical research and deployed systems, where models, specifications, and empirical claims are treated as primary objects, and where persuasion is subordinate to explanation. By anchoring this symposium at the heart of the largest blockchain and cryptocurrency conference in Europe, we are setting a standard for what constitutes legitimate work in this field. TERSE is designed as a space where ideas are rewarded only insofar as they survive contact with properly informed criticism.</p><p>TERSE is a pragmatic effort to provide a public home for the conversations many of us already conduct in smaller rooms. Bonding curve invariants, simulation results, formal verification, and governance trade-offs are already discussed with care in private. TERSE proposes that this mode of discourse should have a permanent place at the center of our industry’s most visible gatherings. Accordingly, we invite researchers and practitioners who seek a forum where technical work is the primary event. Formal pedigree and institutional affiliation are irrelevant. The requirement is the work itself, submitted as a manuscript and presented without promotional intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eXiPNN4DHT8wHrWIqsySw.png" /></figure><p>We welcome submissions across token engineering and cryptoeconomics. Relevant topics include protocol and mechanism design, incentive and market design, verification and simulation, governance and economic security, and research that spans technical, economic, and legal constraints. Both peer-reviewed papers and work in progress are appropriate, provided the submission is research-driven and non-promotional. Review will be attentive and constructive. The criteria are clarity of the research question, defensible assumptions, methodological rigor, and an explicit account of what the results establish and what they do not.</p><p>If a proposal is accepted, the expectation is simple: the talk must teach. A specific project may motivate the work, but the presentation must remain centered on the question, the approach, and the findings. Persuasion must remain subordinate to explanation. TERSE also relies on reciprocity; a rigorous program is a reciprocal exchange of intellectual labor. Authors may be asked to review the work of others with the same care they would expect for their own.</p><p>TERSE is a forum for workers.</p><p>If you have work that deserves a careful hearing, I enthusiastically encourage you to submit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_LEt7-U1H38a5GaKScc-A.png" /></figure><p><strong>Symposium Details</strong></p><p>Submission Deadline: February 20, 2026</p><p>Event Date: March 31, 2026</p><p>Location: Cannes, France (EthCC[9])</p><p>Submission Portal: [<a href="https://www.tokenengineering.net/">LINK</a>]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRJ_9kKOs4o94uKiuec1WA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db401cf6a652" width="1" height="1" alt=""><hr><p><a href="https://blog.bancor.network/the-case-for-constructive-adversarialism-at-mainstream-conferences-db401cf6a652">The Case for Constructive Adversarialism at Mainstream Conferences</a> was originally published in <a href="https://blog.bancor.network/">Bancor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Theory vs Reality]]></title>
            <link>https://medium.com/carbondefi/theory-vs-reality-e4c40625767f?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c40625767f</guid>
            <category><![CDATA[decentralized-exchange]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 04:25:41 GMT</pubDate>
            <atom:updated>2024-02-25T20:53:35.323Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Precision and Accuracy of Carbon DeFi’s Fixed-Point Arithmetic</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jy6977Td6D5Q1Od87QDzZg.png" /></figure><p>My approach to de novo protocol design begins with establishing a theoretical framework. I assume this is common, but I am reluctant to speak for other designers. Speaking only to my experience, this phase of the development process invariably relies on pure algebraic abstraction. The goal is to achieve an exhaustive mathematical description of the protocol’s core methods such that its functionality can be demonstrated symbolically. It is wonderful to arrive at a proven (or, at the very least <em>provable</em>) source of truth with respect to what the expected outcomes are for any conceivable interaction with a newly imagined system. However, as a veteran experimentalist I understand better than most the difference between pen-and-paper theory and the limits of physical reality. For protocol design this is the difference between the immaculate mathematical abstraction of the system and its implementation under the limitations of its host blockchain. With only finite memory and compute cycles at hand, the challenge is to create the best possible approximation of the model while respecting the boundaries of what the network can realistically support. This is no small task. I am very fortunate to be working with talented embedded systems engineers, including and especially Barak Manos, with whom I can collaborate to thread this specific needle.</p><h3>Carbon DeFi in Brief</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GlAB_L7RJApLLVkS1b9UOQ.png" /></figure><p><a href="https://app.carbondefi.xyz/">Carbon DeFi</a> is a token exchange protocol, made to resemble a conventional orderbook in some respects, without completely turning its back on its AMM heritage. Fittingly, the system variables are those required to encapsulate a singular, or series of user-nominated exchange rates and token balances, which are then broadcast to other market participants who may elect to take the tokens and prices on offer. As is customary in DeFi, the exchange is formalized with an invariant function, from which its price quoting and swap functions can be derived:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQwz7z2NzDnnlk_VjALb8w.png" /><figcaption>Invariant Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNT6LUhrRkHMbslIqv4Rxw.png" /><figcaption>Price Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIvZ0sJS5L-uP9sq79K6wA.png" /><figcaption><em>Trade by Source Function (i.e. output amount, given the input amount)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1OeqkR9i4DXwu17WWogIw.png" /><figcaption><em>Trade by Target Function (i.e. input amount, given the output amount)</em></figcaption></figure><p>The <em>a</em>, <em>b</em>, and <em>z</em> terms are constants that describe the relative curvature and size of the bonding curve; <em>z</em> denotes the y-intercept, and <em>a</em> and <em>b</em> are derived from the two price bounds of the range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTtUIc9tct7jAwj4Pqi2dw.png" /><figcaption><em>Exchange Rate Parameter Definitions</em></figcaption></figure><p>In the equations above, (<em>x</em>, <em>y</em>) represent cartesian coordinates for a point that lies on the bonding curve, (Δ<em>x</em>, Δ<em>y</em>) represent token quantities corresponding to a translocation upon the same curve, and Δ<em>x </em>and Δ<em>y </em>have opposite signs. By convention, the swapped token amounts are expressed as unsigned integers, Δ<em>x </em>≥ 0 and Δ<em>y </em>≥ 0. In other words, we adopt a moving frame of reference, such that Δ<em>x </em>represents a number of tokens sent from the market participant to the contract, and Δ<em>y </em>represents a number of tokens sent from the contract to the market participant:</p><ul><li>Following a token exchange, the contract balance of <em>x</em> is <em>x</em> + Δ<em>x.</em></li><li>Following a token exchange, the contract balance of <em>y</em> is <em>y</em> <strong>− </strong>Δ<em>y.</em></li></ul><p>Consequently, the exchange rates for any curve inherit this convention; the exchange rate, ∂<em>y</em>/∂<em>x</em><strong>, </strong>is the drop in the <em>y</em>-balance with respect to some input amount as it approaches zero (Δ<em>x </em>→ 0). The benefit here is that rates are quoted as positive (rather than negative) numbers. While technically incorrect with respect to the invariant, these conventions support standard financial intuition. However, it is important to recognize that this formulation is necessarily numeraire-agnostic, as the <em>y</em>-axis may represent either the “cash” (or “quote”), or “risk” (or “base”) asset. In cases where the <em>y</em>-axis refers to a common numeraire, such as a $USD stablecoin, the price quote is intuitive: ∂<em>y</em>/∂<em>x</em><strong>, </strong>has units of $USD per risk token. However, in cases where the y-axis refers to the risk asset the price quote is inverted: ∂<em>y</em>/∂<em>x </em>has units of risk token per $USD.</p><p>For example, a curve which represents bidding liquidity denominated in USDC for the ETH markets beginning at <em>P_</em>a = 2,200 USDC per ETH and ending at <em>P_</em>b = 1,800 USDC per ETH has intuitive units, and the depletion of the USDC balance on the curve is commensurate with receding bidding prices. Suppose that the curve was initialized with 10,000 USDC of which 5,000 USDC remains. Through application of the price function, the marginal highest bid on the curve, <em>P</em>_m, is found to be ~1,995 USDC per ETH. Whereas <em>P</em>_m is the marginal rate corresponding to the current <em>y</em> balance of the curve, <em>P</em>_a and <em>P</em>_b refer to the marginal rates when <em>y</em> = <em>z</em>, and <em>y</em> = 0, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R66O8JLDo24_ADz4VwkwUw.png" /><figcaption>Figure 1: Invariant and Price Curves for P_a = 2,200 USDC per ETH, P_b = 1,800 USDC per ETH, y = 5,000 USDC and z = 10,000 USDC.</figcaption></figure><p>Consider now how a curve representing asking liquidity might look compared to the bidding liquidity example, above. As per the conventions the curve which offers ETH is necessarily denominated in ETH, and its contract balance is represented on the <em>y</em>-axis. Therefore, the output of the price function (and the variables <em>P</em>_a, <em>P</em>_b, and <em>P</em>_m) are reported in units of ETH per USDC. This can be a little jarring. For example, the curve which offers ETH at a rate beginning at 2,500 USDC per ETH and ending at 3,000 USDC per ETH must use the reciprocals of these values. Suppose that the curve was initialized with 10 ETH, of which 5 ETH remains. The price function returns the marginal lowest ask on the curve, <em>P</em>_m, as 3.66 × 10⁻⁴ ETH per USDC; as before, <em>P</em>_a and <em>P</em>_b refer to the marginal rates when <em>y</em> = <em>z</em>, and <em>y</em> = 0, which are 4.00 × 10⁻⁴ (i.e. 2,500⁻¹) and 3.33 × 10⁻⁴ (i.e. 3,000⁻¹) ETH per USDC, respectively. Note that this arrangement still exhibits the desired behavior; as the ETH balance is depleted, the reciprocal price of ETH is diminished, which is commensurate with higher asking prices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GSk6MT9cYVRzuaz4vL2Qw.png" /><figcaption>Figure 2: Invariant and Price Curves for P_a = 4.00 × 10⁻⁴ (2,500⁻¹) ETH per USDC, P_b = 3.33 × 10⁻⁴ (3,000⁻¹) ETH per USDC, y = 5 ETH and z = 10 ETH.</figcaption></figure><p>If the reader is appropriately motivated, the significance of this parametrization is elaborated in the Carbon DeFi <a href="https://resources.carbondefi.xyz/pages/CarbonWhitepaper.pdf">whitepaper</a>, <a href="https://resources.carbondefi.xyz/pages/CarbonLitepaper.pdf">litepaper</a>, and <a href="https://resources.carbondefi.xyz/pages/CarbonPatent.pdf">invention disclosure</a>. For the present discussion, assume that the user provides all three marginal rates <em>P</em>_a, <em>P</em>_b, and <em>P</em>_m as inputs, along with the token quantity, <em>y</em>, from which the <em>z</em> value must be calculated. In almost all cases, the user elects to have <em>P</em>_m = <em>P</em>_a at the time the curve is initialized, in which case <em>z</em> = <em>y</em>; however, this is not a requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5M82K7xjwuZmSvWFIqNDgQ.png" /><figcaption><em>Curve Size Parameter Definition</em></figcaption></figure><h3>Token Decimals</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dmeV901FNlvCV2y7c7NO9A.png" /></figure><p>For the benefit of the uninitiated, a single token is not what it first appears. Tokens have a property which determines its divisibility, called its “token decimals”. For example, Bitcoin’s decimals are 8, meaning that a single BTC unit is defined as comprising a set of 10⁸ individual parts called “satoshis” or “sats”. Ether’s decimals are 18, meaning that a single ETH unit comprises 10¹⁸ parts called “wei”. Circle’s USD stablecoin uses only 6 decimals, meaning that a single USDC unit comprises 10⁶ parts (also called wei), and so on.</p><p>From the perspective of the exchange system, these smallest indivisible parts are all that matter, and exchange rates are unavoidably expressed in these terms. For example, suppose that 20 ETH is equal in value to 1 BTC (e.g. ETH/USD = $2,500; BTC/USD = $50,000). At the contract level, this translates to 20 × 10¹⁰ ETH wei is equal in value to 1 BTC sat. Since 1 BTC sat is indivisible, BTC-to-ETH exchange is necessarily [for lack of a better word] “chunky”. This forms the basis for further erosion of the perceived accuracy of the system; however, this would be unavoidable even with unlimited storage and computer power.</p><p>To demonstrate how token decimals impact the data available on the smart contracts, the two bonding curves presented above have been recreated here, but this time accounting for the difference in the token decimals. The curve representing bidding liquidity on ETH denominated in USDC, beginning at <em>P_</em>a = 2,200 USDC per ETH and ending at <em>P_</em>b = 1,800 USDC per ETH, initialized with 10,000 USDC, of which 5,000 USDC remains, is now revealed to have a tiny fraction of the naïve exchange rate. At the wei level, the marginal price is no longer ~1,995 USDC per ETH, but 1.995 × 10⁻⁹ USDC wei per ETH wei.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIE-MTvz8ha2fc6KtH-WcQ.png" /><figcaption>Figure 3: Invariant and Price Curves for P_a = 2,200 USDC per ETH, P_b = 1,800 USDC per ETH, y = 5,000 USDC and z = 10,000 USDC, represented at the wei scale.</figcaption></figure><p>The curve representing asking liquidity for ETH denominated in USDC, beginning at 4.00 × 10⁻⁴ (2,500⁻¹) USDC per ETH and ending at 3.33 × 10⁻⁴ (3,000⁻¹) USDC per ETH, initialized with 10 ETH, of which 5 ETH remains, is revealed to exhibit a substantially more aggressive exchange profile compared to the naïve rate. At the wei level, the marginal price is no longer 3.66 × 10⁻⁴ ETH per USDC, but rather 3.66 × 10⁸ ETH wei per USDC wei.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmsG2-KkAIFROtd6K3jtYw.png" /><figcaption>Figure 4: Invariant and Price Curves for P_a = 4.00 × 10⁻⁴ (i.e. 2,500⁻¹) ETH per USDC, P_b = 3.33 × 10⁻⁴ (3,000⁻¹) ETH per USDC, y = 5 ETH and z = 10 ETH, represented at the wei scale.</figcaption></figure><p>Differences in token decimals can alter the effective exchange rates by several orders of magnitude. This presents an interesting challenge, as even common token pairs (e.g. ETH/USDC) can result in exchange rates one might have otherwise concluded were sufficiently unusual to justify ignoring. Unfortunately, no — the scope of the expected input space really is so vast as to include numbers both vanishingly small, and impenetrably large. The challenge is to define the boundaries of what is reasonable and ensure that calculations performed at any point within these bounds result in outputs that closely adhere to the theory, while remaining mindful of the limited computer resources of the network.</p><h3>The Scaling Constant</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXbaAI8O5L9FICdLwyWglw.png" /></figure><p>Fixed point systems only know about integers. For an exchange protocol based on theory that is so thoroughly entrenched in the real numbers, this is a problem. To illustrate, consider that any exchange rate less than one rounds to zero. Given the reciprocal nature of the bidding and asking prices, about half of all exchange rates will default to zero. For example, the value 2/3 cannot be stored in a fixed-point system; however, it can be recreated in-situ by storing the numerator and denominator discretely, (2, 3), and its parts can be summoned when performing further mathematical operations when needed. The approach implemented by <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> is fundamentally the same, save for the fact that the in-situ recreation of the original fraction is abstracted algebraically.</p><p><a href="https://app.carbondefi.xyz/">Carbon DeFi</a> multiplies the rate variables, <em>a</em> and <em>b</em>, by a large constant, <em>C</em>, and records the integer part as the contract variables <em>A</em> and <em>B</em> (n.b. the capitalization is intended to symbolically capture their meaning). Implicitly, these variables represent the numerators of the fractions <em>a</em> = A/<em>C</em> and <em>b</em> = B/<em>C</em>. To recreate<em> a</em> and <em>b</em>, the general formulae are appropriately modified to compensate for the implied denominator, <em>C</em>, which compensates for the scaling-up in <em>A</em> and <em>B</em> and allows these contract variables to be used directly during exchange calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EpG_EYpIb8hlcs8xkzV02Q.png" /><figcaption><em>Exchange Rate Parameter Definitions (Scaling Corrected)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGUG0iZZPhxq-7wkqGM4SA.png" /><figcaption><em>Invariant Function (Scaling Corrected)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R1aPMKqQU1j7_PfRGFtsA.png" /><figcaption><em>Price Function (Scaling Corrected)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xrACyqvrDwTzwOvq4cGAw.png" /><figcaption><em>Trade by Source Function (i.e. output amount, given the input amount) (Scaling Corrected)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfcY9B9_XJsMFEOQQJYWKA.png" /><figcaption><em>Trade by Target Function (i.e. input amount, given the output amount) (Scaling Corrected)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1FKie8zf78-03k-9QytGg.png" /><figcaption><em>Curve Size Parameter Definition (Scaling Corrected)</em></figcaption></figure><h3>Data Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PkriLiT84uD1Tgh7pjSBg.png" /></figure><p>The strategy data is organized into three slots:</p><ul><li><strong>Slot #1</strong>: Contains the <em>y</em>_bid and <em>y_</em>ask values. Each value has 112 bits of allocated memory.</li><li><strong>Slots #2 and #3</strong>: Contains the <em>z</em>_bid, <em>A</em>_bid, and <em>B</em>_bid, and the <em>z</em>_ask, <em>A</em>_ask, and <em>B</em>_ask values, and each slot is exclusive to either the bidding or asking curve. The <em>z</em>_bid and <em>z</em>_ask values have the same 112 bits of allocated memory as the <em>y</em>_bid and <em>y</em>_ask values in Slot #1. The <em>A</em>_bid, <em>B</em>_bid, <em>A</em>_ask, and <em>B</em>_ask values have 54 bits of allocated memory apiece, of which the first 48 bits is reserved for the mantissa (or “significand”) and the remaining 6 bits are reserved for the exponent.</li><li><strong>Unused Bits</strong>: The <em>y</em>_bid, <em>y</em>_ask, <em>z</em>_bid and <em>z</em>_ask values contain a 16-bit appendix, and the <em>A</em>_bid, <em>B</em>_bid, <em>A</em>_ask, and <em>B</em>_ask values contain a 10-bit appendix of unutilized memory. These spaces are envisioned to support other features of the system in the future. Being that this has no bearing on the present discussion, these appendices can safely be ignored.</li></ul><p>This arrangement allows the write operations to be restricted to only one slot in most cases. A trade executed against a strategy necessarily results in changes to both the <em>y</em>_bid and <em>y</em>_ask liquidity values in Slot #1. On occasion, if one of the <em>y</em>_bid or <em>y</em>_ask values exceed its corresponding <em>z</em>_bid or <em>z</em>_ask value, then a second write operation is required to reset the appropriate value in Slot #2 or #3. Therefore, trades executed against a strategy will require data to be overwritten in at most two slots in memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nw_bUcJBBckFEvCePCv96w.png" /><figcaption>Figure 5: <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> strategy data storage and organization</figcaption></figure><h4>Smart Contract Implementation, Fixed-Point Precision, and Relative Error</h4><p>The core object of the <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> protocol is called a <em>strategy</em>, which comprises two different <em>orders </em>represented by two different bonding curves, each representing one of the bid/ask pair. Someone who is quoting the bid and ask prices is called a <em>maker</em>, and the market participant who agrees to an exchange at the quoted price is the <em>taker</em>. There are two types of user-protocol interaction where numeric precision should be scrutinized:</p><ol><li>During strategy creation or editing an existing strategy, wherein the strategy’s owner (i.e. the maker) may provide price inputs of arbitrary precision (highestRate, lowestRate, marginalRate) which must then be transformed into fixed-point format and recorded to the smart contracts.</li><li>During a trade, wherein an outside market participant (i.e. the taker) calls one of the two available trade functions and sends an amount of the <em>source</em> token to the contract in exchange for the <em>target</em> token.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlMrMXM2OauFDTZeLzbOqQ.png" /><figcaption>Figure 6: The two points of user-protocol interaction where precision loss occurs.</figcaption></figure><h4>Strategy Creation and Editing</h4><p>The maker’s purpose [one hopes] is conceived off-chain, where they may imagine an infinitely precise pair of bonding curves that represent their market outlook. Each curve’s parametrization can be described and communicated entirely by the three marginal rates <em>P</em>_a, <em>P</em>_b, and <em>P</em>_m, and the number of tokens, <em>y</em>, to be distributed across each curve. Once received, this data must be processed into the variables <em>A</em>, <em>B</em>, <em>y</em>, <em>z</em>. While these variables may also be infinitely precise with respect to the maker’s imagined strategy, their on-chain representation is limited by the storage allocated to each value. Therefore, this process of collecting and processing the maker’s inputs, and their truncation to fit the storage requirements of the blockchain is an important source of precision loss.</p><p>To understand how this looks in practice, consider an arbitrary set of inputs received from the maker during strategy creation: thehighestRate, lowestRate, marginalRate, and the liquidityvalues. The context is also important. If the maker’s ambition is to buy the risk/base asset, then the liquidity value refers to the cash/quote asset and the exchange rates can be used verbatim; whereas if the maker intends to sell the risk/base asset, then the liquidity value refers to the risk/base asset itself and the exchange rates must be inverted. In both cases, the token decimals and compression of the curve parameters <em>A</em> and <em>B</em> is worth close inspection.</p><p>One of the most challenging pairs in all of DeFi from a precision perspective is Shiba Inu (SHIB, a relatively worthless 18 decimals token) versus wrapped Bitcoin (wBTC, an extremely valuable, 8 decimals token). At the time of writing, the SHIB/USD rate is $0.0₅9756 ($9.756 × 10⁻⁶) and the wBTC/USD rate is $ 51,854.04 ($5.185404 × 10⁴). Therefore, the current wBTC/SHIB market rate is 5,315,092,250.92251 (5.31509225092251 × 10⁹).</p><p>Suppose that a user wants to create a direct market for this pair at the current market rate, offering to buy wBTC with SHIB as the price of SHIB improves in value versus wBTC, with a market depth of 10 billion SHIB tokens or approximately $97,560 USD equivalent value. The following hypothetical inputs represent such a view, and the maker’s arbitrarily precise bonding curve at the wei scale is depicted in Figure 7. Note that we adopt the perspective here that the maker’s off-chain inputs are in the familiar non-wei format, and that the decimal corrections must be applied as part of the input processing.</p><pre>          risk/base token = wBTC<br> risk/base token decimals = 8<br>         cash/quote token = SHIB<br>cash/quote token decimals = 18<br>               order type = “buy wBTC with SHIB”<br><br>  lowestRate = 3,543,394,833.948345819174724191772607317991320232065325065623989176702584205824065767190258<br> highestRate = 7,972,638,376.383778093143129431488366465480470522146981397653975647580814463104147976178081<br>marginalRate = 5,315,092,250.922518728762086287658910976986980348097987598435983765053876308736098650785387<br>   liquidity = 10,000,000,000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4AKD2LXODSvilFVqaNqwsQ.png" /><figcaption>Figure 7: Invariant and Price Curves for lowestRate = 3,543,394,833.9483… SHIB per wBTC, highestRate = 7,972,638,376.3837… SHIB per wBTC, y = 10,000,000,000 SHIB and z = 22,247,448,713.9158… SHIB at the wei scale.</figcaption></figure><p>Here we can examine the translation of the user’s inputs into the curve parameters, and their compression prior to storage. Since this curve has the cash/quote token (SHIB) as its own balance, the rates are used verbatim (i.e. that is, not their reciprocal values), and only adjusted for the decimals of the pair. The sheer size of the result is especially pronounced due to the enormous difference in the token values, which is further amplified by their decimals and the scaling constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xH_idLdKQ-vvJMeKoiVhkQ.png" /><figcaption>Curve Parametrization (Not Inverted)</figcaption></figure><p>The off-chain compression algorithm then converts the rate parameter to an integer and normalizes it by the scaling constant to determine its bit length for truncation. Truncation occurs by bitwise shifting, removing insignificant bits (duh!). The exponent, indicating the value’s scale, is extracted from the truncated value’s bit length. The mantissa is isolated by right-shifting this value by the exponent. Finally, the mantissa and scaled exponent are combined with a bitwise OR, producing a compressed binary representation optimized for minimal storage.</p><p>In other words, (referring only to the integer part of the binary form of the result) the significand is defined as the first 48 digits, which is extracted to be used as the mantissa, and the remaining digits are replaced with zeroes. Then, the trailing zeroes after the 48th digit are counted; the count, expressed as a 6-bit binary number, is extracted as the exponent. The compressed value is then stored as the concatenation of the exponent and the mantissa, in that order.</p><p>I am sincerely hopeful that one of the above descriptions is helpful. Failing that, I am providing the following code snippet from the class I use to perform these analyses, as well as the plain text tables it can produce, which represent each step of the compression sequence for the wBTC/SHIB curve presently under examination for both its <em>B</em> and <em>A</em> parameters.</p><pre>def compress_rate_parameter(<br>    self,<br>    parameter_name: str, <br>    print_process_summary: bool = True<br>    ) -&gt; int:<br>    &quot;&quot;&quot;<br>    ### Compresses a rate parameter for storage in blockchain environments.<br><br>    ## Parameters:<br>    | Parameter Name          | Type      | Description                                                                           |<br>    |-------------------------|-----------|---------------------------------------------------------------------------------------|<br>    | `parameter_name`        | `str`     | The name of the parameter to be compressed.                                           |<br>    | `print_process_summary` | `bool`    | Whether to print a detailed summary of the compression process (default is `True`).   |<br><br>    ## Returns:<br>    | Return Name                | Type  | Description                                                                      |<br>    |----------------------------|-------|----------------------------------------------------------------------------------|<br>    | `compressed_rate_parameter`| `int` | The compressed form of the rate parameter, optimized for blockchain storage.     |<br><br>    ## Notes:<br>    - This method reduces the size of rate parameters, making them suitable for efficient storage and processing on blockchain platforms.<br>    - The compression process involves:<br>        1. Converting the parameter to an integer, if not already.<br>        2. Truncating any trailing zeroes to minimize the parameter&#39;s size.<br>        3. Extracting an exponent representing the scale of truncation.<br>        4. Identifying the mantissa as the significant part of the parameter.<br>        5. Combining the exponent and mantissa into a single integer.<br>    - Optionally, a detailed visual summary of the compression process can be printed, illustrating the transformation of the parameter into its compressed form.<br>    - This method is crucial for understanding the use of smart contract storage, reducing gas costs, and maintaining acceptable accuracy.<br>    &quot;&quot;&quot;<br>    rate_parameter_int = int(self.maker_precise_curve_parameters[parameter_name])<br>    number_of_bits = (rate_parameter_int // self.scaling_constant_int).bit_length()<br>    truncated_rate_parameter = (rate_parameter_int &gt;&gt; number_of_bits) &lt;&lt; number_of_bits<br>    exponent = (truncated_rate_parameter // self.scaling_constant_int).bit_length()<br>    mantissa = truncated_rate_parameter &gt;&gt; exponent<br>    compressed_rate_parameter = mantissa | (exponent * self.scaling_constant_int)<br>    if print_process_summary:<br>        self.print_compression_process_summary(parameter_name,<br>                                               rate_parameter_int,<br>                                               truncated_rate_parameter,<br>                                               exponent,<br>                                               mantissa,<br>                                               compressed_rate_parameter)<br>    return compressed_rate_parameter</pre><pre>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                                                     | Note          |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|      precise B parameter (decimal float) | &gt;&gt;&gt; 1675519805183645805377564.303617077025442675500104314972513464861602177426342456097867234892029625106 |               |<br>|            B parameter (decimal integer) | &gt;&gt;&gt; 1675519805183645805377564                                                                             |               |<br>|             B parameter (binary integer) | &gt;&gt;&gt;       101100010110011100001110001010010111110100010001001111111110010101111100000011100               | (max 96 bits) |<br>|   truncated B parameter (binary integer) | &gt;&gt;&gt;       101100010110011100001110001010010111110100010001000000000000000000000000000000000               | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;       ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑               |               |<br>|                                          | &gt;&gt;&gt;       |-----------------significand------------------||--------trailing-zeroes--------|               |               |<br>|              B exponent (binary integer) | &gt;&gt;&gt; 100001                                                                                                | (max 6 bits)  |<br>|              B mantissa (binary integer) | &gt;&gt;&gt;       101100010110011100001110001010010111110100010001                                                | (max 48 bits) |<br>|  compressed B parameter (binary integer) | &gt;&gt;&gt; 100001101100010110011100001110001010010111110100010001                                                | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                |               |<br>|                                          | &gt;&gt;&gt; |expt||-------------------mantissa-------------------|                                                |               |<br>| compressed B parameter (decimal integer) | &gt;&gt;&gt; 9483730408799505                                                                                      |               |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+</pre><pre>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                                                    | Note          |<br>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+<br>|      precise A parameter (decimal float) | &gt;&gt;&gt; 837759902591822902688782.151808538512721337750052157486256732430801088713171228048933617446014812554 |               |<br>|            A parameter (decimal integer) | &gt;&gt;&gt; 837759902591822902688782                                                                             |               |<br>|             A parameter (binary integer) | &gt;&gt;&gt;       10110001011001110000111000101001011111010001000100111111111001010111110000001110               | (max 96 bits) |<br>|   truncated A parameter (binary integer) | &gt;&gt;&gt;       10110001011001110000111000101001011111010001000100000000000000000000000000000000               | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;       ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑               |               |<br>|                                          | &gt;&gt;&gt;       |-----------------significand------------------||-------trailing-zeroes--------|               |               |<br>|              A exponent (binary integer) | &gt;&gt;&gt; 100000                                                                                               | (max 6 bits)  |<br>|              A mantissa (binary integer) | &gt;&gt;&gt;       101100010110011100001110001010010111110100010001                                               | (max 48 bits) |<br>|  compressed A parameter (binary integer) | &gt;&gt;&gt; 100000101100010110011100001110001010010111110100010001                                               | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                               |               |<br>|                                          | &gt;&gt;&gt; |expt||-------------------mantissa-------------------|                                               |               |<br>| compressed A parameter (decimal integer) | &gt;&gt;&gt; 9202255432088849                                                                                     |               |<br>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+</pre><p>In addition to the compression of these curve parameters, only the integer parts of the <em>y</em> and <em>z</em> values are stored. While this is obvious for <em>y</em>, which represents the SHIB token balance of the curve (in wei units), it is still worth raising as the maker be unaware of the decimals of the token they are using and provide an off-chain input that implies divisibility beyond that supported by the token contract (e.g. wBTC beyond the 8th decimal place). While <em>z</em> has an explicit correspondence with <em>y</em> and must also be an integer, it is also computed from the marginal rate user input. Therefore, its rounding will also have an impact on the overall precision of the system — albeit a negligible one. The error caused by rounding the <em>y</em> and <em>z </em>values and resulting from a compression/decompression cycle of the <em>A</em> and <em>B</em> values can be examined directly versus the maker’s arbitrarily precise inputs by comparing the digits in-place.</p><pre>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|                Parameter | Value                                                                                                 |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|        y precise (maker) | 10000000000000000000000000000                                                                         |<br>|                          | |||||||||||||||||||||||||||||                                                                         |<br>| y fixed point (contract) | 10000000000000000000000000000                                                                         |<br>|                          |                                                                                                       |<br>|        z precise (maker) | 22247448713915890490986420373.52945695982973740328335064216346283625480188728657513269929716552320115 |<br>|                          | |||||||||||||||||||||||||||||                                                                         |<br>| z fixed point (contract) | 22247448713915890490986420373                                                                         |<br>|                          |                                                                                                       |<br>|        A precise (maker) | 837759902591822902688782.151808538512721337750052157486256732430801088713171228048933617446014812554  |<br>|                          | ||||||||||||||::::||:::|                                                                              |<br>| A fixed point (contract) | 837759902591821830684672                                                                              |<br>|  A compressed (contract) | 9202255432088849                                                                                      |<br>|                          |                                                                                                       |<br>|        B precise (maker) | 1675519805183645805377564.303617077025442675500104314972513464861602177426342456097867234892029625106 |<br>|                          | |||||||||||||||::::|::::|                                                                             |<br>| B fixed point (contract) | 1675519805183643661369344                                                                             |<br>|  B compressed (contract) | 9483730408799505                                                                                      |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+</pre><p>Be reminded that a <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> strategy is composed of two bonding curves, each taking a different side of the market. It is worthwhile to consider the opposite order type — one which offers wBTC liquidity in exchange for SHIB as the price of wBTC appreciates relative to SHIB — because it represents the opposite extreme of the curve parametrization.</p><p>Suppose that the maker includes the following order as part of their strategy, representing the opposite side of the market with a depth of 4 wBTC tokens or approximately $207,416 USD equivalent value:</p><pre>          risk/base token = wBTC<br> risk/base token decimals = 8<br>         cash/quote token = SHIB<br>cash/quote token decimals = 18<br>               order type = “sell wBTC for SHIB”<br><br>  lowestRate = 7,972,638,376.383778093143129431488366465480470522146981397653975647580814463104147976178081<br> highestRate = 15,945,276,752.76755618628625886297673293096094104429396279530795129516162892620829595235616<br>marginalRate = 10,630,184,501.84503745752417257531782195397396069619597519687196753010775261747219730157077<br>   liquidity = 4</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VPFytAy7mYJFhIuDlj9Zg.png" /><figcaption>Figure 7: Invariant and Price Curves for lowestRate = 7,972,638,376.3837… SHIB per wBTC, highestRate = 15,945,276,752.7675… SHIB per wBTC, y = 4 wBTC and z = 7.3721… wBTC at the wei scale. Note that the curve rates P_a, P_m, and P_b are inverted with respect to the user inputs.</figcaption></figure><p>Note that since the <em>y</em> balance of the curve refers to the risk/base asset, the price quotes and token decimals must be converted to their reciprocals, which can be abstracted in the math as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBJ9Q6U_g_rfWMNtHr3V4Q.png" /><figcaption>Curve Parametrization (Inverted)</figcaption></figure><p>With these numbers in-hand, the same compression algorithm and rounding of the <em>y</em> and <em>z</em> values apply, exactly as before.</p><pre>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                                                     | Note          |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|      precise B parameter (decimal float) | &gt;&gt;&gt; 22290.70278229099528962926755992160011182305315686523376722634019307511285975496714971660409421763525 |               |<br>|            B parameter (decimal integer) | &gt;&gt;&gt; 22290                                                                                                 |               |<br>|             B parameter (binary integer) | &gt;&gt;&gt;       101011100010010                                                                                 | (max 96 bits) |<br>|   truncated B parameter (binary integer) | &gt;&gt;&gt;       101011100010010                                                                                 | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;       ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                                                 |               |<br>|                                          | &gt;&gt;&gt;       |-significand-|                                                                                 |               |<br>|              B exponent (binary integer) | &gt;&gt;&gt; 000000                                                                                                | (max 6 bits)  |<br>|              B mantissa (binary integer) | &gt;&gt;&gt;       101011100010010                                                                                 | (max 48 bits) |<br>|  compressed B parameter (binary integer) | &gt;&gt;&gt; 000000101011100010010                                                                                 | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                                                 |               |<br>|                                          | &gt;&gt;&gt; |expt||--mantissa---|                                                                                 |               |<br>| compressed B parameter (decimal integer) | &gt;&gt;&gt; 22290                                                                                                 |               |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+</pre><pre>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                                                    | Note          |<br>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+<br>|      precise A parameter (decimal float) | &gt;&gt;&gt; 9233.11140725261452182535808827061525937857598134623803709959495937678947350425791519043211464010009 |               |<br>|            A parameter (decimal integer) | &gt;&gt;&gt; 9233                                                                                                 |               |<br>|             A parameter (binary integer) | &gt;&gt;&gt;       10010000010001                                                                                 | (max 96 bits) |<br>|   truncated A parameter (binary integer) | &gt;&gt;&gt;       10010000010001                                                                                 | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;       ↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                                                 |               |<br>|                                          | &gt;&gt;&gt;       |significand-|                                                                                 |               |<br>|              A exponent (binary integer) | &gt;&gt;&gt; 000000                                                                                               | (max 6 bits)  |<br>|              A mantissa (binary integer) | &gt;&gt;&gt;       10010000010001                                                                                 | (max 48 bits) |<br>|  compressed A parameter (binary integer) | &gt;&gt;&gt; 00000010010000010001                                                                                 | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                                                 |               |<br>|                                          | &gt;&gt;&gt; |expt||--mantissa--|                                                                                 |               |<br>| compressed A parameter (decimal integer) | &gt;&gt;&gt; 9233                                                                                                 |               |<br>+------------------------------------------+----------------------------------------------------------------------------------------------------------+---------------+</pre><p>What should be noted here is that the <em>A</em> and <em>B</em> curve parameters are sufficiently small to fit entirely within the 48-bit memory allocation of the mantissa, and the compressed value is identical to the integer part of the input. In other words, the scaled-up value is stored as-is, without compression. This is true for all rate parameters on any token pair, smaller than 48-bits. While the precision loss associated with compression is forgone, this does not mean that the process is necessarily more precise. On the contrary, the discarded fractional component may represent a more significant source of error, as its relative size with respect to the integer being stored is orders of magnitude larger (which is partly why low decimals tokens such as wBTC and USDC are such a nuisance in exchange protocols).</p><pre>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|                Parameter | Value                                                                                                 |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|        y precise (maker) | 400000000                                                                                             |<br>|                          | |||||||||                                                                                             |<br>| y fixed point (contract) | 400000000                                                                                             |<br>|                          |                                                                                                       |<br>|        z precise (maker) | 737215598.8403066345843944226900997996236027110871949096129123470537482453137996501292832036260560230 |<br>|                          | |||||||||                                                                                             |<br>| z fixed point (contract) | 737215598                                                                                             |<br>|                          |                                                                                                       |<br>|        A precise (maker) | 9233.11140725261452182535808827061525937857598134623803709959495937678947350425791519043211464010009  |<br>|                          | ||||                                                                                                  |<br>| A fixed point (contract) | 9233                                                                                                  |<br>|  A compressed (contract) | 9233                                                                                                  |<br>|                          |                                                                                                       |<br>|        B precise (maker) | 22290.70278229099528962926755992160011182305315686523376722634019307511285975496714971660409421763525 |<br>|                          | |||||                                                                                                 |<br>| B fixed point (contract) | 22290                                                                                                 |<br>|  B compressed (contract) | 22290                                                                                                 |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+</pre><p>Note that after the data is processed and stored, the original inputs are unknowable to anyone except the maker who produced them. This is an important observation because it adds ambiguity to the precision measurement as it relates to trade outputs, and to what we should refer to as the “precise standard”. For completeness’ sake, this investigation will include two different measurements: one from the perspective of the maker’s arbitrarily precise inputs, and one with the assumption that the data stored on the contract is itself, arbitrarily precise. In other words, the result of a trade executed against the strategy as it exists on Ethereum will be compared to:</p><ul><li>The same trade executed on a hypothetical system with unlimited memory and where tokens have infinite decimals, where the maker’s curve was created with perfect precision with respect to their inputs. That is, we will measure the error with respect to what the maker knows (referred to as maker-precise).</li><li>The same trade executed on the same hypothetical system as above, but where the maker’s inputs are substituted for the rounded and compressed/decompressed data of the fixed-point system. That is, we will measure the error with respect to what the smart contract knows (referred to as contract-precise).</li></ul><h3>Performing Exchange</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kQZha62b0FkZ7h6YihGh7w.png" /></figure><p>From the perspective of the smart contract implementation, it is important to note that all rounding is performed in such a way as to always benefit the maker. That is, when the output of a trade function is rounded from its theoretical contract-precise value to an integer, it is always in the direction of a slightly less desirable exchange rate from the taker’s perspective. This approach annuls any attempt by an adversary to engineer an input whereby they might receive more than the theoretically allowed token amount.</p><p>There are two trade functions available on <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s smart contracts:</p><ul><li>tradeBySource (i.e. <em>amount-out-given-amount-in</em>) always returns a number less than or equal to the contract-precise theoretical amount.</li><li>tradeByTarget (i.e. <em>amount-in-given-amount-out</em>) always returns a number greater than or equal to the contract-precise theoretical amount.</li></ul><p>The purpose of this analysis is to examine how and to what extent information is eroded between conceiving a trading strategy, communicating it to the <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> contracts, and its execution. With that in mind, the perspective of the taker is not really within scope — nor should it be. Unlike the maker, the taker can read the information from the contracts and simulate the inputs and outputs with 100% precision. Having said this, I do consider the effective price differences on execution resulting from the choice of either tradeBySourceor tradeByTarget to be worth a considered analysis.</p><h4>Trade by Source</h4><p>Be reminded that the theory requires:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xrACyqvrDwTzwOvq4cGAw.png" /><figcaption><em>Trade by Source Function (i.e. output amount, given the input amount) (Scaling Corrected)</em></figcaption></figure><p>Which can be functionally composed such that each intermediate operation does not exceed the 256-bit EVM mandate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7-BWqQe1jdhIecM4ISfgrg.png" /><figcaption>Functional composition of the <em>Trade by Source Function (1 of 3)</em></figcaption></figure><p>The final trade value is then computed from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aipYcnmNCXhyH1LW9d-ZyA.png" /><figcaption>Functional composition of the <em>Trade by Source Function (2 of 3)</em></figcaption></figure><p>Which is equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8qB97H_WxoiNRT98Mx3_A.png" /><figcaption>Functional composition of the <em>Trade by Source Function (3 of 3)</em></figcaption></figure><p>The 256-bit limitation for the uint256 data type necessitates careful arithmetic management to prevent overflow while maintaining calculation precision. The smart contract’s approach is designed to navigate these constraints effectively.</p><p>The architecture utilizes mulDivC functions in certain computations (<em>f</em>₃, <em>f</em>₄, <em>f</em>₆, and <em>f</em>₇) to permit intermediate values to momentarily surpass the 256-bit boundary, ensuring that while the numerator in these operations may exceed the limit, the final results conform to the uint256 range. The final step also utilizes a mulDivC function to compute the scaled-down <em>C</em>²<em>z</em>² term, and uses a utilizes a mulDivF function to compute the scaled-down Δ<em>x </em>(<em>Ay + Bz</em>)<em> </em>term. This method balances precision with the technical limitations of Ethereum, adopting a strategic approach to expression refactoring when necessary.</p><p>The computation of the final trade value, Δ<em>y, </em>reflects <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s defensive programming: it underestimates the numerator and overestimates the denominator, and the final division utilizes a mulDivF function to round the result towards zero. This tactic intentionally biases rounding errors in favor of the maker, a measure taken to prevent giving undue advantage to the taker owing to calculation imprecision. This choice underscores a principle of transaction security and fairness innate to <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s implementation.</p><p>Overall, the contract demonstrates a balance between retaining calculation precision and preventing overflow, while adhering to Ethereum’s specifications and ensuring transaction integrity. By carefully managing arithmetic operations, the contract maintains a high degree of accuracy and reliability of its core functions without venturing out-of-bounds.</p><p>Returning to the example above, where the maker has offered SHIB tokens in exchange for wBTC tokens, we can simulate an exchange to reveal the implemented fixed-point precision result, and measure the relative error compared to the hypothetical maker-precise, and contract-precise outputs. For this example, assume that the taker wishes to send 0.32100123 wBTC tokens against the maker’s order, in return for the appropriate number of SHIB tokens as dictated by the general formula. The fixed-point smart contract implementation returns 1,654,355,822.074328684134994879 SHIB tokens, which is within 2.481523 parts per Quadrillion of the maker’s arbitrarily precise expectation, and within 26.631197 parts per Octillion of the arbitrarily precise result referencing only the data available stored on the contract itself. Again, the fixed-point calculation returns a number that is very slightly less than either of the precise calculations, meaning the taker trades at a slight disadvantage.</p><pre>Function Called: trade_by_source<br><br>Trade Input (Token Wei): 32100123 wBTC (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output SHIB (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1654355822074332789456944072.627885974582462779091418036616284712304625160064989689902030257444409839 |<br>|                                  | ||||||||||||||:::|::::|:|:::.::|::::|::::::::|:::|::::::::::::::::::::::::::::::::::::::::::::::::::: |<br>|   Arbitrary Precision (Contract) | 1654355822074328684134994923.057476573629605278371744220559652825496956981343545367598264564735765621 |<br>|                                  | |||||||||||||||||||||||||:::                                                                          |<br>| Fixed-point Precision (Contract) | 1654355822074328684134994879                                                                          |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 0.32100123 wBTC<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output SHIB                                                                                     |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1654355822.074332789456944072627885974582462779091418036616284712304625160064989689902030257444409839 |<br>|                                  | ||||||||||.||||:::|::::|:|:::::|::::|::::::::|:::|::::::::::::::::::::::::::::::::::::::::::::::::::: |<br>|   Arbitrary Precision (Contract) | 1654355822.074328684134994923057476573629605278371744220559652825496956981343545367598264564735765621 |<br>|                                  | ||||||||||.|||||||||||||||:::                                                                         |<br>| Fixed-point Precision (Contract) | 1654355822.074328684134994879                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 2.481523 parts per Quadrillion<br>Fixed-Point vs Arbitrary Precision (Contract): 26.631197 parts per Octillion</pre><p>Now, referring to the opposite order within the strategy, where the maker has offered wBTC tokens in exchange for SHIB tokens, assume that the taker wishes to exchange 10,000,000 SHIB the appropriate number of wBTC tokens as dictated by the general formula. The fixed-point smart contract implementation returns 0.00094062 wBTC tokens, which is within 60.433641 parts per Million of the maker’s arbitrarily precise expectation, and within 4.523412 parts per Million with respect to the contract data. Again, the fixed-point calculation returns a number that is very slightly less than either of the precise calculations, which is the desired behavior.</p><pre>Function Called: trade_by_source<br><br>Trade Input (Token Wei): 10000000000000000000000000 SHIB (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output wBTC (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 94067.68485269045831388380332087239085166052240773657843008681176800858259514885400558683400775461902 |<br>|                                  | ||||:.:::::::::::::|:::::::|:::::::::|:||::::|:::|::|:::::::::::::::::::::::::::::||:::::::::::::::|: |<br>|   Arbitrary Precision (Contract) | 94062.42548314780701261249837916821935266674645663587209179344662617977680268270640530830378232720800 |<br>|                                  | |||||                                                                                                 |<br>| Fixed-point Precision (Contract) | 94062                                                                                                 |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 10000000 SHIB<br><br>+----------------------------------+-----------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output wBTC                                                                                         |<br>+----------------------------------+-----------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 0.0009406768485269045831388380332087239085166052240773657843008681176800858259514885400558683400775461902 |<br>|                                  | |.|||||||::::::::::::::|:::::::|:::::::::|:||::::|:::|::|:::::::::::::::::::::::::::::||:::::::::::::::   |<br>|   Arbitrary Precision (Contract) | 0.00094062425483147807012612498379168219352666746456635872091793446626179776802682706405308303782327208   |<br>|                                  | |.||||||||                                                                                                |<br>| Fixed-point Precision (Contract) | 0.00094062                                                                                                |<br>+----------------------------------+-----------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 60.433641 parts per Million<br>Fixed-Point vs Arbitrary Precision (Contract): 4.523412 parts per Million</pre><h4>Trade by Target</h4><p>Be reminded that the theory requires:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfcY9B9_XJsMFEOQQJYWKA.png" /><figcaption><em>Trade by Target Function (i.e. input amount, given the output amount) (Scaling Corrected)</em></figcaption></figure><p>Which can be functionally composed such that each intermediate operation does not exceed the 256-bit mandate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRlpskofK4NOX_J7QvOWeA.png" /><figcaption>Functional composition of the <em>Trade by Target Function (1 of 3)</em></figcaption></figure><p>The final trade value is then computed from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m64JKgy6EDKtnzxxWlL8zQ.png" /><figcaption>Functional composition of the <em>Trade by Target Function (2 of 3)</em></figcaption></figure><p>Which is equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z4MysoLBut6ekhoGN1wSw.png" /><figcaption>Functional composition of the <em>Trade by Target Function (3 of 3)</em></figcaption></figure><p>In the computation of Δ<em>x, </em>the implementation approach diverges from that of Δ<em>y </em>in a critical aspect: the direction of rounding errors. This difference is a consequence of the reciprocal nature of these two functions. For Δ<em>x, </em>which calculates the quantity of tokens a trader must send to the contract, the approach intentionally overestimates the numerator and underestimates the denominator, with the overall result being rounded up. This method is a deliberate inversion of the error biases applied in the Δ<em>y </em>calculation.</p><p>This inversion is necessary to align the contract’s defensive programming with the transaction’s direction — ensuring that any rounding errors do not unjustly penalize the maker by requiring them to overpay. By overestimating the numerator and underestimating the denominator in the final computation, and rounding the result up, the contract aims to slightly favor the maker in the presence of calculation imprecision. Whereas the taker, who can observe the trade result prior to committing to the transaction, still get exactly the exchange rate they expected. This careful adjustment ensures that the contract remains equitable and avoids inadvertently disadvantaging users, maintaining fairness, transparency and integrity in all transactions that occur between users of the protocol.</p><p>Revisiting again the scenario where SHIB tokens are offered by the maker in exchange for wBTC tokens, let us undertake another exchange simulation to measure the precision loss of the fixed-point arithmetic, but this time using tradebyTarget. Consider a situation where the taker’s goal is to secure 1,654,355,822.074328684134994879 SHIB tokens from the maker’s market, meaning she queries how many wBTC tokens must be relinquished from her wallet to the maker’s order to complete the trade. The smart contract’s fixed-point precision calculation determines that 0.32100123 wBTC tokens are needed. This outcome reveals a difference of only 2.559216 parts per Quadrillion with respect to the maker’s exact calculations, and a difference of only 27.464979 parts per Octillion while taking the curve parametrization on the smart contract at face-value. Notably, the amount of wBTC tokens calculated for the exchange slightly overshoots the arbitrarily precise amount, subtly disadvantaging the taker, akin to the earlier observations.</p><pre>Function Called: trade_by_target<br><br>Trade Input (Token Wei): 1654355822074328684134994879 SHIB (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output wBTC (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 32100122.99999991784886412852376781350937039114955097711412169114634721350541566773448401388225188758 |<br>|                                  | ||||||||.|||||||::::::::::::::::::::::|:|:|:::::::|:|::::|:::|::::|::::::|:|::::::::::::|:::::::|:::: |<br>|   Arbitrary Precision (Contract) | 32100122.99999999999999999911837079065977833525874017487511909540535177810240205627620351953898580437 |<br>|                                  | |||||||:                                                                                              |<br>| Fixed-point Precision (Contract) | 32100123                                                                                              |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 1654355822.074328684134994879 SHIB<br><br>+----------------------------------+--------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output wBTC                                                                                      |<br>+----------------------------------+--------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 0.3210012299999991784886412852376781350937039114955097711412169114634721350541566773448401388225188758 |<br>|                                  | |.|||||||||||||||::::::::::::::::::::::|:|:|:::::::|:|::::|:::|::::|::::::|:|::::::::::::|:::::::|:::: |<br>|   Arbitrary Precision (Contract) | 0.3210012299999999999999999911837079065977833525874017487511909540535177810240205627620351953898580437 |<br>|                                  | |.|||||||:                                                                                             |<br>| Fixed-point Precision (Contract) | 0.32100123                                                                                             |<br>+----------------------------------+--------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 2.559216 parts per Quadrillion<br>Fixed-Point vs Arbitrary Precision (Contract): 27.464979 parts per Octillion</pre><p>Lastly, and again turning our attention to the opposite order, where wBTC tokens are offered from the maker in exchange for SHIB tokens, consider a scenario where the taker aims to acquire 0.00094062 wBTC tokens using SHIB tokens. The taker requests the quantity of SHIB tokens that should be sent to the contract; in response, the smart contract’s fixed-point execution returns that 9,999,954.763923315127815869 SHIB tokens are needed. This result demonstrates a discrepancy of 55.916021 parts per Million from what was anticipated by the maker’s high-precision calculation and deviates by 40.578300 parts per Octillion when aligned against the contract data assuming arbitrary runtime resources. Consistent with prior examples, the computed SHIB token quantity for the trade is marginally greater than both precise evaluations, subtly positioning the taker at a slight disadvantage.</p><pre>Function Called: trade_by_target<br><br>Trade Input (Token Wei): 94062 wBTC (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output SHIB (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 9999395637511301625506302.622771540656487995730800965380663671805155126785782213292248238466542297775 |<br>|                                  | ||||:::::::::|:::|:::::::.:::::::::::::::::::::::|::::::|:::::|:::::::::::::::|::|:::::::::|::|:::::: |<br>|   Arbitrary Precision (Contract) | 9999954763923315127815868.594218836892670162259140677147615505874263278292550311194597366596202611817 |<br>|                                  | ||||||||||||||||||||||||:                                                                             |<br>| Fixed-point Precision (Contract) | 9999954763923315127815869                                                                             |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 0.00094062 wBTC<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output SHIB                                                                                     |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 9999395.637511301625506302622771540656487995730800965380663671805155126785782213292248238466542297775 |<br>|                                  | ||||:::.::::::|:::|::::::::::::::::::::::::::::::|::::::|:::::|:::::::::::::::|::|:::::::::|::|:::::: |<br>|   Arbitrary Precision (Contract) | 9999954.763923315127815868594218836892670162259140677147615505874263278292550311194597366596202611817 |<br>|                                  | |||||||.|||||||||||||||||:                                                                            |<br>| Fixed-point Precision (Contract) | 9999954.763923315127815869                                                                            |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 55.916021 parts per Million<br>Fixed-Point vs Arbitrary Precision (Contract): 40.578300 parts per Octillion</pre><h4>Testing to Failure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ulx-Leha1EWL6RBp2Dn_tQ.png" /></figure><p>What I have tried to demonstrate above is that <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s implementation can handle even the most extreme of token exchange rates, such as that exhibited by high-decimals, relatively worthless tokens such as Shiba Inu, versus low-decimals, exceedingly valuable tokens such as wBTC. This begs the question as to where the limits of reasonable behavior are. Any system based on finite computer resources will have a limited scope of precision and accuracy, and it is a worthwhile endeavor to discover those boundaries.</p><p>This is not as easy as it sounds.</p><p>The parametrization of <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s bonding curves is four-dimensional (<em>A</em>, <em>B</em>, <em>y</em>, <em>z</em>), and while trade inputs are only one-dimension, there are two different kinds:tradeBySource (Δ<em>x</em>) and tradeByTarget (Δ<em>y</em>), which makes for a six-dimensional hypervolume of possible input space. Accounting for the data compression and storage, the upper bound on the rate parameter is 281,474,976,710,655 × 2⁴⁸, which in terms of price quoting and/or range width is 79,228,162,514,263,774,643,590,529,025 wei/wei units. Taken together, the input space is absurdly large — but it can be meaningfully searched.</p><p>When<a href="https://app.carbondefi.xyz/"> Carbon DeFi</a> was still in its gestational stage, I developed a suite of analysis tools to systematically map the input space (terabytes of data) and report problematic regions requiring further attention. Among its goals are to characterize how precision and accuracy change as a function of the inputs, and to discover situations where the effects of rounding have not had the desired result (i.e. the taker has an advantage over the maker). Fortunately, the only examples that exist for reversal of the rounding error benefit are nonsensical. Regardless, these families of input types are worth acknowledging and characterizing. The following example is representative of the set.</p><pre>          risk/base token = ABCD<br> risk/base token decimals = 18<br>         cash/quote token = WXYZ<br>cash/quote token decimals = 18<br>               order type = &quot;buy ABCD with WXYZ&quot;<br><br>  lowestRate = 4.0000000000000000000000000000000000000000000000000000000000000000000000000000000000<br> highestRate = 4.0000000000000000000000000000000001925929944387235792646606569178402423858642578125<br>marginalRate = 4.0000000000000000000000000000000001925929944387235792646606569178402423858642578125<br>   liquidity = 1</pre><p>The first thing to notice is that the difference between the input rates is very small — beneath the resolution that can be achieved after compression/decompression of the exchange range width parameter, <em>A</em>. Therefore, it rounds to zero. There is no such issue for the <em>B</em> parameter.</p><pre>+------------------------------------------+-----------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                       | Note          |<br>+------------------------------------------+-----------------------------------------------------------------------------+---------------+<br>|      precise A parameter (decimal float) | &gt;&gt;&gt; 1.35525271560688049999999999999999998368673883000368970659882225079E-20 |               |<br>|            A parameter (decimal integer) | &gt;&gt;&gt; 0                                                                       |               |<br>|             A parameter (binary integer) | &gt;&gt;&gt;       0                                                                 | (max 96 bits) |<br>|   truncated A parameter (binary integer) | &gt;&gt;&gt;       0                                                                 | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;                                                                         |               |<br>|                                          | &gt;&gt;&gt;       |significand|                                                     |               |<br>|              A exponent (binary integer) | &gt;&gt;&gt; 000000                                                                  | (max 6 bits)  |<br>|              A mantissa (binary integer) | &gt;&gt;&gt;       0                                                                 | (max 48 bits) |<br>|  compressed A parameter (binary integer) | &gt;&gt;&gt; 000000                                                                  | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑                                                                  |               |<br>|                                          | &gt;&gt;&gt; |expt||mantissa|                                                        |               |<br>| compressed A parameter (decimal integer) | &gt;&gt;&gt; 0                                                                       |               |<br>+------------------------------------------+-----------------------------------------------------------------------------+---------------+</pre><pre>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|                                 Variable | Value                                                                                                     | Note          |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+<br>|      precise B parameter (decimal float) | &gt;&gt;&gt; 562949953421312.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000 |               |<br>|            B parameter (decimal integer) | &gt;&gt;&gt; 562949953421312                                                                                       |               |<br>|             B parameter (binary integer) | &gt;&gt;&gt;       10000000000000000000000000000000000000000000000000                                              | (max 96 bits) |<br>|   truncated B parameter (binary integer) | &gt;&gt;&gt;       10000000000000000000000000000000000000000000000000                                              | (max 96 bits) |<br>|                                          | &gt;&gt;&gt;       ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↑↑                                              |               |<br>|                                          | &gt;&gt;&gt;       |-----------------significand------------------||trailing-zeroes|                               |               |<br>|              B exponent (binary integer) | &gt;&gt;&gt; 000010                                                                                                | (max 6 bits)  |<br>|              B mantissa (binary integer) | &gt;&gt;&gt;       100000000000000000000000000000000000000000000000                                                | (max 48 bits) |<br>|  compressed B parameter (binary integer) | &gt;&gt;&gt; 000010100000000000000000000000000000000000000000000000                                                | (max 54 bits) |<br>|                                          | &gt;&gt;&gt; ↑↑↑↑↑↑↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓                                                |               |<br>|                                          | &gt;&gt;&gt; |expt||-------------------mantissa-------------------|                                                |               |<br>| compressed B parameter (decimal integer) | &gt;&gt;&gt; 703687441776640                                                                                       |               |<br>+------------------------------------------+-----------------------------------------------------------------------------------------------------------+---------------+</pre><pre>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|                Parameter | Value                                                                                                 |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+<br>|        y precise (maker) | 1000000000000000000                                                                                   |<br>|                          | |||||||||||||||||||                                                                                   |<br>| y fixed point (contract) | 1000000000000000000                                                                                   |<br>|                          |                                                                                                       |<br>|        z precise (maker) | 1000000000000000000                                                                                   |<br>|                          | |||||||||||||||||||                                                                                   |<br>| z fixed point (contract) | 1000000000000000000                                                                                   |<br>|                          |                                                                                                       |<br>|        A precise (maker) | 1.35525271560688049999999999999999998368673883000368970659882225079E-20                               |<br>|                          | :                                                                                                     |<br>| A fixed point (contract) | 0                                                                                                     |<br>|  A compressed (contract) | 0                                                                                                     |<br>|                          |                                                                                                       |<br>|        B precise (maker) | 562949953421312.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000 |<br>|                          | |||||||||||||||                                                                                       |<br>| B fixed point (contract) | 562949953421312                                                                                       |<br>|  B compressed (contract) | 703687441776640                                                                                       |<br>+--------------------------+-------------------------------------------------------------------------------------------------------+</pre><p>WhentradeBySourceis called with its theoretical maximum input (with respect to the contract variables), 0.25 ABCD, there is nothing remarkable about the output:</p><pre>Function Called: trade_by_source<br><br>Trade Input (Token Wei): 250000000000000000 ABCD (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1000000000000000000.000000000000000024074124304840447408082582114730029428887840659198167255476383850 |<br>|                                  | |||||||||||||||||||                                                                                   |<br>|   Arbitrary Precision (Contract) | 1000000000000000000                                                                                   |<br>|                                  | |||||||||||||||||||                                                                                   |<br>| Fixed-point Precision (Contract) | 1000000000000000000                                                                                   |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 0.25 ABCD<br><br>+----------------------------------+------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ                                                                                    |<br>+----------------------------------+------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1.00000000000000000000000000000000002407412430484044740808258211473002942888784065919816725547638385 |<br>|                                  | |                                                                                                    |<br>|   Arbitrary Precision (Contract) | 1                                                                                                    |<br>|                                  | |                                                                                                    |<br>| Fixed-point Precision (Contract) | 1                                                                                                    |<br>+----------------------------------+------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 24.074124 parts per Undecillion<br>Fixed-Point vs Arbitrary Precision (Contract): Negligible error</pre><p>Exceeding the maximum input is impracticable, as the maker’s strategy will simply not have any more tokens to give, and the transaction will revert. Save for the fact that it is completely meaningless to do so, continuing to increase thetradeBySourceinput amount up to <em>exactly</em> 2× its theoretical limit reveals something unexpected. First, examine the outcome at some negligible amount smaller than 2×.</p><pre>Function Called: trade_by_source<br><br>Trade Input (Token Wei): 499999999999999999 ABCD (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1999999999999999996.000000000000000000000000000000000192592994438723577720347745950573968894003767416 |<br>|                                  | |||||||||||||||||||                                                                                   |<br>|   Arbitrary Precision (Contract) | 1999999999999999996                                                                                   |<br>|                                  | |||||||||||||||||||                                                                                   |<br>| Fixed-point Precision (Contract) | 1999999999999999996                                                                                   |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 0.4999999999999999999999999999999999999999999999999999999999999999999999999999999999999 ABCD<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ                                                                                     |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1.999999999999999996000000000000000000000000000000000192592994438723577720347745950573968894003767416 |<br>|                                  | |.||||||||||||||||||                                                                                  |<br>|   Arbitrary Precision (Contract) | 1.999999999999999996                                                                                  |<br>|                                  | |.||||||||||||||||||                                                                                  |<br>| Fixed-point Precision (Contract) | 1.999999999999999996                                                                                  |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): 96.296497 parts per Septendecillion<br>Fixed-Point vs Arbitrary Precision (Contract): Negligible error</pre><p>The error is significantly reduced compared to the maker-precise result, and the rounding is still in the right direction. Now, increasing by an amount so small I would consider it meaningless if I didn’t already know the outcome:</p><pre>Function Called: trade_by_source<br><br>Trade Input (Token Wei): 500000000000000000 ABCD (wei scale)<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ (wei scale)                                                                         |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1999999999999999999.999999999999999999999999999999999999999999999999998840873077910180889673968511799 |<br>|                                  | :::::::::::::::::::                                                                                   |<br>|   Arbitrary Precision (Contract) | 2000000000000000000                                                                                   |<br>|                                  | |||||||||||||||||||                                                                                   |<br>| Fixed-point Precision (Contract) | 2000000000000000000                                                                                   |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br>Trade Input (Ignoring Decimals): 0.5 ABCD<br><br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|                        Precision | Trade Output WXYZ                                                                                     |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br>|      Arbitrary Precision (Maker) | 1.999999999999999999999999999999999999999999999999999999999999999999998840873077910180889673968511799 |<br>|                                  | :                                                                                                     |<br>|   Arbitrary Precision (Contract) | 2                                                                                                     |<br>|                                  | |                                                                                                     |<br>| Fixed-point Precision (Contract) | 2                                                                                                     |<br>+----------------------------------+-------------------------------------------------------------------------------------------------------+<br><br><br>Fixed-Point vs Arbitrary Precision (Maker): Negligible error<br>Fixed-Point vs Arbitrary Precision (Contract): Negligible error</pre><p>The error is now so small as to have become nearly immeasurable. More importantly, the rounding is now in favor of the taker compared to the maker’s precise calculations; compared to the contract variables, there is no difference. As it happens, this is a general phenomenon. There exists an input space where, if the range width is sufficiently narrow so as to round to nothing on the contracts and we ignore the upper bound on the tradeBySourceinput, it is possible to achieve a rounding error that the maker would argue is in the wrong direction. Fortuitously this phenomenon is contained to nonsense inputs, and so has no bearing on the real-world functioning of <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s Smart contracts. I raise it here for the benefit of academic curiosity, and in the hope that it may shed light on other unexpected behaviors that may affect other systems designs.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPsL43mZ2j87jF1sKRaH3g.png" /></figure><p>The exploration into <a href="https://app.carbondefi.xyz/">Carbon DeFi</a>’s fixed-point arithmetic and its impact on trade precision reveals both the challenges and achievements in supporting financial models within the constraints of blockchain technology. Through careful design and strategic implementation, <a href="https://app.carbondefi.xyz/">Carbon DeFi</a> navigates the inherent limitations of fixed-point computation, ensuring that the protocol remains equitable for both makers and takers. This study underscores the importance of precision in decentralized finance, illustrating that even minute discrepancies can have tangible effects on trading outcomes. As blockchain technology evolves, so too will the methodologies to optimize precision and efficiency in DeFi protocols, further bridging the gap between theory and execution.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c40625767f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/theory-vs-reality-e4c40625767f">Theory vs Reality</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 2023 Pre-Christmas PlayStation 5 (Blu-Ray Edition) eBay Bonding Curve]]></title>
            <link>https://medium.com/carbondefi/the-2023-pre-christmas-playstation-5-blu-ray-edition-ebay-bonding-curve-79e7a713148a?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e7a713148a</guid>
            <category><![CDATA[automatic-market-maker]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 15:43:51 GMT</pubDate>
            <atom:updated>2023-12-18T16:32:03.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VR0gKQBsOY7gNCBRuRSURA.png" /></figure><p>The emergence of DeFi has introduced a wave of marketing language that is both creatively enthusiastic and, in many cases, ultimately devoid of substance. Terms that once held well-defined meanings, such as “capital efficiency”, “fees”, “loss versus rebalancing”, and “toxic flow”, have become embroiled in the hubris of DeFi’s marketing hive mind. It is conspicuous that much of the industry’s success can be attributed to social media, where appeals to emotion and the distinctly human desire to be a member of the tribe are the primary focus. Consequently, it should come as no surprise that very simple financial concepts have taken on unnecessary ambiguity as communities in DeFi repurpose them to attract more tribe members. In this context, the precise communication of a financial concept becomes secondary to its emotional and social resonance.</p><p>Moreover, a notable aspect of this dynamic is the attitude of the DeFi users themselves. There is a discernible demand for access to sophisticated financial protocols, coupled with a resistance to engaging with the educational efforts necessary to use these tools effectively. Users often seek the benefits of DeFi participation without investing the time to understand the underlying principles. This paradoxical expectation has led to a form of communication within the DeFi space that prioritizes social engagement and often deliberately overlooks the more substantive, albeit less glamorous, foundational aspects of DeFi protocols.</p><p>The irony is that, while mundane, the underlying concepts are not at all challenging. However, I suspect that the added level of abstraction afforded by their context inside of the blockchain narrative can make it difficult to see the forest for the trees. To strip away the layers of ambiguity and social influence standing in the way of what should be accessible knowledge, I am going to focus on a more comfortable and practical analogy: the eBay market for the PlayStation 5 Blu-Ray Edition. This comparison with respect to the “Buy It Now” feature for merchants on eBay is quite nearly perfect; however, for the bidding prices we are going to take some poetic license by imagining a restructuring of eBay that, quite frankly, would bring some interesting new functionality to their platform. This approach aims to offer a more objective understanding of the core principles of exchange protocols, untangled from the tribalism and postmodern subjection of the communities that wield them.</p><h4>The PlayStation 5 (Blu-Ray Edition) eBay Market</h4><p>I am deliberately constraining the scope of eBay’s market for PlayStation 5’s (on the maker side) to something relatively straight-forward. I have no intention of aggregating this in any meaningful sense; the objective of this discussion is to arrive at a useful understanding of blockchain exchange primitives, not to embark on a thorough investigation of secondary consumer electronics markets. To collect a homogenous sample, I am focusing on the Blu-Ray Edition for the sole reason that there are more of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LKVsXrnxDlZHDw_WcDxhw.png" /><figcaption>Figure 1: eBay PlayStation 5 market search.</figcaption></figure><p>I checked each listing to confirm that it was what it claimed; in some cases the disc drive needed to be selected from a dropdown menu to get the correct quote price. At least half of these listings are bundled together with a game. Anecdotally, whether a game is included with the bundle has zero correlation with the unit price. For each listing I recoded the quote and shipping value, and the number of units still for sale. There were two instances where a purchase of more than one console resulted in a discounted price on a per-unit basis. For these I assumed buying all the listed stock, thereby achieving the maximum discount. In another two instances, the number of units for sale was simply listed as “more than ten”. In these cases, I recorded the number of units as 11 and moved on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIR6wAeqsKc7NQQa6bZquQ.png" /><figcaption>Figure 2: Typical eBay PlayStation 5 seller’s page.</figcaption></figure><h4><strong>The PlayStation 5 (Blu-Ray Edition) eBay Depth Chart</strong></h4><p>Imagine that we live in a world where market takers (i.e. people buying PlayStation 5s) are rational, and consistently make good decisions. Completely divorced from reality though this may be, it is a necessary concession when analyzing the available market. We therefore assume that when interacting with the market, all else being equal, the taker will elect to purchase the most inexpensive PlayStation 5 first. After the transaction is made, that stock is removed from the marketplace. If there are more units available at the same price, the next consumer is unaffected; however, if the stock at the lowest price is depleted, then the next consumer is forced to interact with the next available unit at whatever its listing price is.</p><p>This situation is absolutely within the grasp of everyone using DeFi:</p><ul><li>There are a limited number of PlayStation 5s on the market.</li><li>They are spread out over a range of asking prices by vendors.</li><li>If you want to buy a PlayStation 5, it is sensible to buy one at the lowest available asking price.</li><li>After all the PlayStation 5s available at a single price point are consumed,</li><li>the next available asking price will be greater than the one that was just exhausted.</li></ul><p>It is reasonable to ask how much retail business the PlayStation 5 market on eBay can sustain at a certain price level, or all price levels. To investigate, imagine buying each PlayStation 5 listed on eBay one by one, beginning from the lowest listing price and working your way up. As you perform each transaction, record the listing price for the PlayStation 5 you just bought, and the running total of all the money you have spent purchasing them. The plot of this data is called a market depth chart.</p><p>The eBay PlayStation 5 market depth is an important characteristic, because it reports how much the asking price of a PlayStation 5 is likely to increase given a surge in consumer demand. For example, imagine that you were tasked with buying a bunch of PlayStation 5s for Santa Claus to deliver to well-behaved human offspring at Christmas. Santa’s instructions are that you can only purchase a PlayStation 5 if it costs $1,200.00 AUD or less. From the chart below, you can tell immediately that you are going to spend $131,126.32 AUD buying PlayStations (including postage!); although, since the depth is reported in dollars it is not immediately clear precisely how many PlayStations you are buying. All you know is that after you are done, the first available price to the next consumer will be &gt;$1,200.00 AUD. Therefore, market depth charts are more concerned with cash flow than the commodity it is paired with.</p><p>Again, I posit that this is not a challenging concept for DeFi users:</p><ul><li>From examination of the depth chart, we can conclude that:</li><li>a purchase of $131,126.32 AUD worth of PlayStation 5s from eBay will</li><li>move the asking price from $720.95 AUD to &gt; $1,200 AUD,</li><li>(i.e. &gt; +66.45%).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aoZ6BFljFsGYyC5I_1lwA.png" /><figcaption>Figure 3: eBay PlayStation 5 asking depth.</figcaption></figure><h4><strong>The PlayStation 5 (Blu-Ray Edition) eBay Bonding Curve</strong></h4><p>To determine how many PlayStation 5s will be adorning the televisions of deserving children (within budget), we can simply plot the loss of PlayStation 5 inventory by eBay merchants as a function of the increase in their cash balances. The starting PlayStation 5 inventory is 181 units, and the remaining inventory as the collective cash balance of the merchants approaches $131,126.32 AUD is 54 units; therefore, only 181–54 = 127 special children are receiving a PlayStation 5 for Christmas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrBYBquotBtRtLmH9vBGyw.png" /><figcaption>Figure 4: eBay PlayStation 5 asking bonding curve.</figcaption></figure><p>This kind of plot has become known as a “bonding curve” throughout DeFi. Notice that in this form the price data is sacrificed, so by itself is not especially useful. However, paired with the depth chart, the two together provide a phenomenally detailed snapshot of the current market. That is, assuming you are considering buying a <a href="https://phys.org/news/2010-12-air-playstation-3s-supercomputer.html">suspicious quantity</a> of PlayStations from eBay in a short timeframe. This is an important point: these kinds of analyses assume that you are buying all units at once before the vendors have time to react. If you are buying PlayStation 5s one-at-a-time, slowly over the course of hours or days, it is reasonable to expect that the vendors might move their prices up in anticipation of the oncoming demand. This kind of market reaction does not apply to AMMs, and so is outside the scope of the discussion.</p><p>While Santa’s instructions were to only purchase PlayStation 5s under the predicate that each one cost $1,200.00 AUD or less, we have still only spent a total of $132,126.32 AUD and acquired 127 consoles, which is an average of $1,032.49 AUD per unit. If we interpret Santa’s instructions to mean that we should spend no more than an <em>average</em> of $1,200.00 AUD per PlayStation 5, then we can afford to take the entire PlayStation 5 market at an average price per unit of $1,096.02 and still be under budget.</p><p>While this is a more common depiction in DeFi, I suspect that it is still a source of confusion for many:</p><ul><li>The bonding curve is a plot of the eBay merchant’s PlayStation 5 inventory versus their cash balances.</li><li>As PlayStation 5s are sold, they are removed from the inventory (i.e. -ΔPlayStation 5)</li><li>and $AUD is added to the cash balance (i.e. +ΔAustralian Dollars).</li><li>The average price per PlayStation 5 when buying multiple units is simply the total units received from the vendor divided by the total cash paid.</li></ul><h4><strong>The eBay We All Deserve but Can’t Have</strong></h4><p>As it stands, eBay allows consumers to interact with vendors in a variety of ways.</p><ol><li>The most common is the situation already explored in the previous section, where vendors list their PlayStation 5s with specific asking prices, and consumers can browse the available asking prices before deciding to purchase.</li><li>Long ago, the most common interaction was via the auction mechanic, where the vendor provides the item and consumers bid against each other.</li><li>The third and final supported interaction is where the vendor may elect to accept offers — meaning that the item is listed with a certain asking price, but the consumer can negotiate a lower price.</li></ol><p>Imagine a fourth mode of interaction, where consumers could list their cash with the “price” being an item they wish to purchase. Distinct from the third type of interaction, instead of offering cash to only the vendors who have elected to allow price negotiations, you could offer cash to <em>all</em> vendors, simultaneously. Such a system would align well with free market ideals; allowing consumers to list cash offers could lead to a more competitive and efficient market for PlayStation 5s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MhRB98EWW37nH0Ai9iqdw.png" /><figcaption>Figure 5: Imagined eBay PlayStation 5 bidding page.</figcaption></figure><p>While this fourth type of interaction is currently absent (eBay, if you are reading this — call me), the auction component of the system for which they were once known is still alive and well, albeit <a href="https://community.ebay.com.au/t5/eBay-Announcements-and-Seller/Ebay-is-no-longer-relavent-as-an-Auction-site/td-p/2024951">much less popular</a> than it was in its glory days. The auction mechanics are recorded and apparently freely auditable directly via the page wherein an auction is taking place (although, a login is required). I expanded the scope of the PlayStation 5 market probe to include those listings currently being actively bid on, and scraped their bidding history to get an idea of what the other side of the market might look like, were those without a PlayStation allowed to offer their cash directly to those with one, on their own terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pf-WBZWoSlk3hwYqCuOCA.png" /><figcaption>Figure 6: Typical eBay PlayStation 5 bidding history.</figcaption></figure><p>I didn’t spend a huge amount of time on this — nor could I if I wanted to. At the time of writing there were only five relevant auctions, and only two of them were being bid on, and only by 12 different users. The other three auctions had their commencing bids (i.e. the one requested by the merchant) set well out of the money with respect to the market already available, which explains the lack of activity. Regardless, I collected 30 data points that represent individual prices that users had expressed an interest in transacting at. Never mind that we are demonstrably double counting the cash market; just pretend that each bid was from a unique user and that their offers were posted as listings on eBay proper, instead of being asked to compete for the same items in a live-auction format.</p><p>Thus, we can construct a depth chart as we have previously, but this time on the bids side. Imagine selling PlayStation 5s into this market, where consumers are offering cash via an eBay listing. Start by selling your PlayStation 5 inventory, one by one, beginning from the highest available bidding price and working your way down. As with the previous exercise, as you perform each transaction, record the bidding price for the PlayStation 5 you just sold and the running total of all the cash you have collected from consumers in the process. Since PlayStation 5 sellers taking this market are motivated to get the highest price, the bidding depth chart is mirrored relative to the asking depth chart; the market depth to sell PlayStation 5s improves as we approach lower prices.</p><p>Nothing surprising or difficult here, either:</p><ul><li>There are a limited amount of cash offers on the market.</li><li>They are spread out over a range of bidding prices by consumers.</li><li>If you want to sell a PlayStation 5, it is sensible to sell it at the highest available bidding price.</li><li>After all the cash offers at a single price point have been taken,</li><li>the next available bidding price will be less than the one that was just exhausted.</li></ul><p>This depth chart may be of interest if you have a large stockpile of PlayStation 5s, as it reports how much cash you could obtain quickly if you had to liquidate your inventory. For example, imagine <a href="https://www.ccn.com/news/ftx-liquidation-plan-protect-market/">you are tasked with liquidating Santa’s reserves of PlayStations</a> after the <a href="https://en.wikipedia.org/wiki/Sam_Bankman-Fried">United States Department of Justice charges him</a> with wire fraud, money laundering, and conspiracy thereof. Your instructions are to not relinquish any PlayStations for less than $600.00 AUD apiece. Again, the depth chart self-reports that you will be able to liquidate $7,054.50 AUD worth of consoles, but it doesn’t tell you how many consoles that equates to.</p><p>To determine how many PlayStation 5s will be unloaded onto the market, we can simply plot the loss of Australian Dollars by consumers as a function of function of their increase in PlayStation 5s. Consumers begin with $16,673.50 in bidding liquidity, and their PlayStation 5 inventory approaches 10 as we take $7,054.50 AUD of their market. Therefore, we can afford to liquidate 10 PlayStation 5s without selling one beneath the $600 per unit mandate. As before, if we interpret our instructions as meaning an average of $600 AUD per unit, we can afford to take $12,725.95 of the cash market for an average of $606.00 AUD per console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wYkw2edfXDivDyE4hs24g.png" /><figcaption>Figure 7: eBay PlayStation 5 bidding depth.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAJxgRPBoyFgjkMd4Nb0ig.png" /><figcaption>Figure 8: eBay PlayStation 5 bidding bonding curve.</figcaption></figure><h4><strong>Taking Both Sides of eBay’s PlayStation 5 Market</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6kFApxud2dT1i3Q3DnFRg.png" /></figure><p>It might be reasonable to expect that between holiday seasons the demand for PlayStation 5s could begin to wane — but the overheads of operating a retail electronics outlet remain consistent. When business is slow and with the tax season approaching, there could be an opportunity to squeeze the retailers for their precious PlayStation 5 inventory. Consider this: in a market that’s not as buoyant, the urgency to maintain cash flow might compel some retailers to turn to the cash offers in our re-imagined version of eBay, and this is where a discerning trader finds their niche.</p><p>Imagine then, strategically acquiring PlayStation 5s from these retailers when they’re most eager to sell. The real opportunity unfolds as the year progresses towards December, a time traditionally marked by a surge in demand, often driven by parents seeking to fulfill holiday wishes.</p><p>Now suppose that you could refuse delivery on the PlayStations you acquire and can instead opt to warehouse them free-of-charge in eBay’s depots. Then, after each transaction your eBay page immediately and automatically lists the console you just bought with more optimistic holiday season prices. Later, when you find a buyer at your asking price, the cash you receive immediately goes back on your eBay page, again offering cash for PlayStation 5s at a lower bidding price, in cycles, ad infinitum.</p><p>This is not as absurd as you might think. This practice of taking both sides of a market simultaneously, and the profit motive for doing so, is the business of <a href="https://en.wikipedia.org/wiki/Market_maker">professional market makers</a>, typically large financial institutions or firms. However, in our context, both with respect to the PlayStation 5 on eBay and exchange primitives for cryptocurrency tokens on a blockchain, the scaled-down version of professional market making is nearly indistinguishable from the business of a pawn broker. I concede that the scale, regulatory environment, and nature of transactions (individual consumer goods vs. standardized financial instruments) are quite different, but the profit mechanism is literally identical:</p><ul><li>Offer cash at a bidding price for something while</li><li>simultaneously offer the thing you are bidding on at a higher asking price.</li></ul><p>I know it sounds trite — but there really is only one way to make money trading: <a href="https://medium.com/carbondefi/buy-low-sell-high-repeat-c6b0c64bc953">Buy Low, Sell High, Repeat</a>. It’s all there is, it’s all we’ve got, it’s not complicated, and it never was. Whether it is buying and selling PlayStation 5s on eBay via the warehousing method described above or providing token liquidity to a decentralized exchange, the financial fundamentals are indistinguishable. And I can prove it.</p><h4><strong>Using eBay as an Automatic Market Maker for PlayStation 5s</strong></h4><p>The canonical automatic market maker hasn’t changed at all since its inception in 2017. Its most familiar form is the one consisting of exactly two assets with equal portfolio weights, also known as the “constant product” or the <em>xy</em> = <em>k</em> pricing algorithm. This is the context where most DeFi users will have first encountered the concept of a “fee”; the common understanding is that use of their liquidity incurs additional charges from market participants, which accumulates to the value of their portfolio. Unfortunately, this description completely obfuscates the true nature of their activities. There is no such thing as a “fee” on a decentralized exchange, any more than there is on eBay. In fact, there is nothing stopping us from re-creating the <em>xy</em> = <em>k</em> AMM on our improved version of eBay (i.e. delivery refusal, warehousing, and the ability to list cash in exchange for goods).</p><p>For this exercise, we will begin with a PlayStation 5 inventory of 100 units, and $158,000 AUD in cash. Assume that the mid-market price for a new console is $1,580.00 AUD, and that we acquired all consoles in the inventory at this price. Using the <em>xy</em> = <em>k </em>pricing algorithm with a <em>δ </em>term of 0.2 (aka the “fee” parameter; 0.2 is unusually high but it doesn’t matter here), we would list our first PlayStation 5 for $2,000 AUD, and we would list our first cash offer at $1,251.49 AUD. Meaning, we are offering to buy a PlayStation 5 from anyone who would wish to sell one to us for $1,251.49 AUD and, simultaneously, we are offering to sell a PlayStation 5 to anyone who wants one for $2,000 AUD, thereby achieving a bid-ask spread of $2,000.00 AUD — $1,251.49 AUD = $748.51 AUD. Those are just our highest bidding and lowest asking prices; we have 99 more consoles in our inventory and another $156,748.50 AUD in cash reserves with which to create a market:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYd3A858vbWsIXRICIOvWw.png" /><figcaption>Table 1: The PlayStation 5 xy = k AMM bids and asks table.</figcaption></figure><p>Due to a quirk of the <em>xy</em> = <em>k</em> pricing algorithm, the last PlayStation 5 in the inventory is priced at infinity dollars, and the second to last unit carries an asking price of more than a third of a billion dollars. However, our cash bids are limitless; the 5189th consecutive bid is the last time we offer the market more than $1.00 AUD for a PlayStation 5.</p><p>I have shown these rows for completeness’ sake only. It is obvious that some of these prices are absurd. If we limit our market making to the first five rows, then we would only need $6,042.47 AUD and five PlayStation 5s, which would emulate an “amplified liquidity” position (also known as “concentrated liquidity”), meaning that despite having significantly less inventory and cash reserves, it continues to behave as though it contains 100 units and $158,000 AUD with respect to the <em>xy</em> = <em>k</em> model. The amplified version simply restricts the available market depth to whatever cash and inventory is provided without affecting the bidding and asking prices. Therefore, with fewer resources you could service the same market — provided it doesn’t overwhelm your bidding and asking prices. The DeFi community has somewhat misleadingly co-opted the term “<a href="https://www.mosaic.tech/financial-metrics/capital-efficiency">capital efficiency</a>” to describe this behavior, perhaps to invoke ideas of financial growth and profitability. “However, it can be inferred from its usage that the appropriation of the term in DeFi specifically compares one pricing model to another:</p><ul><li>One pricing model is more capital efficient than another if</li><li>by default it offers higher bidding prices and lower asking prices</li><li>normalized to the same inventory and cash balances.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOv_ZvwHoz-oqodu4hR7Hw.png" /><figcaption>Figure 9: xy = k AMM PlayStation 5 bidding and asking depth.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3kIjTs4PzvhuZKr1fQScQ.png" /><figcaption>Figure 10: Concentrated AMM PlayStation 5 bidding and asking depth.</figcaption></figure><p>Since our eBay store is adopting the prototypical Concentrated AMM pricing model, it is important to acknowledge that as the market takes PlayStation 5s from our inventory (i.e. as our asking prices are taken), our cash reserves are increasing, but also our bidding prices are updated. In a continuous liquidity situation the spread between the marginal bid and ask is a constant proportion, and is simple to calculate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KR43prWqhf0JSfDpcL3lWQ.png" /></figure><p>However, since customers are expecting to transact in whole PlayStation 5s, instead of fractions of a PlayStation 5, we will need to correct for price slippage, which in turn requires the relative amplification of our inventory to be appropriately accounted for (i.e. the reduced slippage of the concentrated position):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMxmSKzyF3USOK_X8FUEWw.png" /></figure><p>where:</p><ul><li><em>x</em> is the remaining PlayStation 5 inventory,</li><li><em>x</em><a href="https://www.bing.com/ck/a?!&amp;&amp;p=5aa8e0d009ea5882JmltdHM9MTcwMTgyMDgwMCZpZ3VpZD0yYzFiYTQ1Mi1kYmVmLTYwZjEtMzgxOS1iNjBkZGFmZjYxMDAmaW5zaWQ9NTIzNQ&amp;ptn=3&amp;ver=2&amp;hsh=3&amp;fclid=2c1ba452-dbef-60f1-3819-b60ddaff6100&amp;psq=subscript+0+character&amp;u=a1aHR0cHM6Ly93d3cuaG90c3ltYm9sLmNvbS9zeW1ib2wvc3Vic2NyaXB0LXplcm8&amp;ntb=1">₀</a> is the initial PlayStation 5 inventory (i.e. 5, in this example),</li><li><em>δ </em>is the [unhelpfully named] “fee” parameter, in our case set to 0.2, and</li><li><em>A</em> is the amplification coefficient, in this case 100/5 = 20.</li></ul><p>Again, this is not difficult. I am aware that an equation or two may inspire fear and anxiety for many — but hear me out; all we are doing is establishing the rules for our eBay page(s) that:</p><ul><li>adjust the bidding prices <em>up</em> as buyers take our PlayStation 5 market;</li><li>adjust the asking prices <em>down</em> as sellers take our cash market.</li></ul><p>This gets easier with illustration. Suppose that after setting up our five asking prices and five bidding prices (Table 1) we make our first transaction: a PlayStation 5 seller takes our highest bidding price; our PlayStation inventory increases by one and we lose $1,251.49 AUD from the cash reserves. The other cash listings are unaffected; the next highest bid remains at $1,229.40. However, as the newly acquired PlayStation 5 is added to our store inventory, not only is it appended to the existing asks, but every single asking price is also adjusted according to the general spread formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGxlrw5zGOj6RYxtYH6IyA.png" /><figcaption>Table 2: The PlayStation 5 bids and asks table after taking the first bid.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ot42arlL-V4GbDy0g3pOhQ.png" /><figcaption>Figure 11: Updates to the asking depth after taking the first bid.</figcaption></figure><p>Assume that the PlayStation 5 seller’s appetite continues to increase, and they begin to accept the lower bidding prices, until there is only 1 PlayStation 5 left in the inventory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_thviZldQcC58FODJdZcOg.png" /><figcaption>Table 3: The PlayStation 5 bids and asks table after taking the first four bids.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccYlwihyKodcv8Q5ABdc1g.png" /><figcaption>Figure 12: Updates to the asking depth after taking the first four bids.</figcaption></figure><p>At this stage, all we have done is acquire four additional PlayStation 5s at an average of cost of $1,218.95 AUD per unit. Note that the model here is 1:1 with an AMM on the blockchain, save for some minor implementation-specific details. We listed five PlayStation consoles at five different prices, and four of them were bought. As a specialist PlayStation 5 pawn broker on eBay, and equally, as a token liquidity provider to a decentralized exchange, there are only two things you care about:</p><ul><li>The acquisition costs and</li><li>the sale price,</li><li>not necessarily in that order.</li></ul><p>This is the critical realization, and what I believe to be the most thoroughly misunderstood concept in all DeFi: the question as to what the fee earnings are up to this point. The short answer is that there is no fee; <em>liquidity providers to AMMs do not charge fees</em>, and so the “fee earnings” calculation is devoid of meaning. A better question — one which is more founded in financial reality, is whether the <em>trading strategy</em> is profitable. The answer is that before we can claim to have turned a profit, we need to sell the PlayStation 5 inventory back to the market at a higher price than it was acquired for.</p><p>That is really all there is to this. Bid low on PlayStation 5s when sellers are getting anxious and ask high when the market demand is increasing. There is no other profit mechanism.</p><p>Suppose that sometime after the market takes most of our cash reserves, the nine PlayStation 5s we have listed start to receive some interest. Then, finally, a PlayStation 5 buyer takes our lowest asking price; our PlayStation inventory decreases by one and our cash reserves recover by $1,862.82 AUD. The other PlayStation 5 listings are unaffected; the next lowest ask remains at $1,904.02 AUD. However, as the cash comes in, it is immediately added to cash listings and the bidding prices are updated according to the general spread formula. This is the exact reverse of the situation where our cash market was being taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i01Es0KEBotvVeKC38AHCQ.png" /><figcaption>Table 4: The PlayStation 5 bids and asks table after taking the first ask.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMIo9z78zd_VzgqsCRB-kA.png" /><figcaption>Figure 13: Updates to the bidding depth after taking the first ask.</figcaption></figure><p>Assume that interest in the PlayStation 5 market continues to develop, and buyers begin to accept the higher asking prices until there are only four PlayStations left in the inventory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjqrXR8LlX1RuI2wtjEUOQ.png" /><figcaption>Table 5: The PlayStation 5 bids and asks table after taking the first five asks.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHRwyDYTMDajiivSmw3QTQ.png" /><figcaption>Figure 14: Updates to the bidding depth after taking the first five asks.</figcaption></figure><p>There is exactly one correct way to evaluate the performance of this trading strategy, and there is nothing subjective about it:</p><ul><li>We started with $13,942.47 AUD in cash,</li><li>exchanged $7,900.00 AUD for five PlayStation 5s at the mid-market rate ($1,580.00 AUD), then</li><li>used the remaining $6,042.47 AUD to set up a cash market on eBay for an additional five consoles, while</li><li>simultaneously making the market for PlayStation 5s starting at an asking price of $2,000.00 AUD.</li><li>We acquired four additional consoles at an average price of $1,218.96 AUD per console, then</li><li>sold five consoles at an average price of $1,947.93 AUD.</li><li>The final balance sheet is $10,906.28 AUD in cash, and</li><li>four PlayStation 5s with a combined nominal value of $8,143.20 <em>if we trust the last unit sale price</em>,</li><li>culminating in a portfolio value of $19,049.48 and an unrealized profit of $5,107.01 (36.6%).</li></ul><p>Note that the profit here is still unrealized. The starting cash balance was $13,942.47 and we still only have $10,906.28 in reserve. The four unsold consoles are still an outstanding liability until their value is consolidated back into Australian Dollars.</p><p>This is literally everything you ever needed to know about providing liquidity to a market — be it for PlayStation 5s, or via the ETH/USDC liquidity pool on your favourite AMM. My ambition with this illustration is not only to demonstrate that the common understanding of the “fee” parameter on an AMM is dangerously removed from reality, but also to bring attention to the fact of the matter — <em>liquidity provisioning is a trading strategy</em>. There is no ambiguity, no benefit of the doubt, nothing is left to interpretation.</p><p>Some things simply <em>are</em>, regardless of how we feel about it.</p><h4><strong>The Hubris of the Defeated</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5a2rHkpoTEPdJp99VpIsA.jpeg" /></figure><p>As with the misappropriation of the term “capital efficiency”, use of the term “toxic flow” (image related) in DeFi has become all but meaningless. That is not to say that toxic flow is not a real phenomenon — it absolutely is, and its effects range from a market nuisance to financial devastation. I’d like to extend my appreciation to the original author of <a href="https://theforexgeek.com/toxic-order-flow/"><em>Toxic Order Flow</em></a> on theforexgeek.com for providing some much needed clarity, and from whom I have paraphrased the following bullets regarding what constitutes legitimate toxic order flow.</p><ul><li><strong>Spoofing</strong>: This involves a trader placing an order without any intention of letting it execute. Their goal is to falsely signal strong demand or supply, manipulating the asset’s price. After the price shifts favorably, they retract their order, capitalizing on this artificial movement.</li><li><strong>Layering</strong>: Like spoofing, layering consists of setting up several orders at varied price points. This creates an illusion of significant trading activity, swaying the asset’s price. The trader then withdraws these orders, benefiting from the resultant price shift.</li><li><strong>Marking the Close</strong>: Here, a trader executes a substantial order at or near the market’s closing time. This strategy aims to affect the closing price, which can also misrepresent the asset’s demand or supply, influencing its price.</li><li><strong>Order Stuffing</strong>: This tactic involves flooding the market with numerous orders in a brief timeframe. The overload can cause processing delays and disrupt the normal pricing of the asset.</li><li><strong>Front Running</strong>: In this scenario, a trader exploits advance knowledge of an impending order. By acting on this information, they position themselves to profit from the price changes that will follow once the large order is executed.</li><li><strong>Insider Trading</strong>: This is trading based on confidential, non-public information. For instance, a company insider might buy stock before a positive announcement, aiming to sell it post-announcement for a profit.</li></ul><p>In contrast, the concept of toxic flow in DeFi is, for lack of a better description, an imagined external tormentor that is summoned by those who end up on the losing side of bad trade (by providing liquidity to it). It is a convenient scape goat for bad businesses who get upset when they exit from their PlayStation 5 inventory only to see those same units for sale the following day at mark-up. Or, conversely, the pawn brokers who bought those PlayStations only to find that it is impossible to flip them for a profit later.</p><p>I speculate that there is, in fact, a good reason for this term to have entered the DeFi vocabulary in the context of AMMs and liquidity provisioning. Consider that despite my best efforts to make the material presented here as accessible as possible, for many DeFi users the subject matter is simply not interesting (no judgement!). My suspicion is that the people that belong to this category share a significant part of their Venn Diagram with those who don’t understand why their LP positions are losing money. Armed with only the dangerous half-knowledge afforded them by the paid shills on Twitter and YouTube, failure to perform financially could seem deeply mysterious. Together with the common misconception that losses on an LP position can be partially or wholly attributed to the actions of arbitrageurs, a crowd-sourced vision of the bogeyman on whom we can pin our accusations of unfair practices does emerge.</p><p>But this is a mistake.</p><p>The analysis in the previous section is perfectly valid on its own and does not require any additional context. In short, your trading profits and losses are what they are, irrespective of the motivations that drive eBay’s buyers and sellers to trade with you. The true toxic flow is not from those who interacted with a market you created — it is from those who would prefer the convenience of selling you on the idea of “capital efficiency” and “fees” and then never explain to you what either of those things really mean.</p><h4><strong>Conclusion</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zoMHwf4a8xqZozlhDKO89A.png" /></figure><p>In this examination, the tangible case of eBay’s PlayStation 5 market has been utilized to elucidate the financial principles underlying liquidity provision in Automated Market Makers (AMMs). This analysis, while comprehensive and perhaps somewhat technical, demonstrates that these concepts are accessible to individuals engaging with DeFi primitives on the blockchain.</p><p>The DeFi sector is often characterized by the use of marketing buzzwords and emotive narratives. While these elements play a role in fostering enthusiasm and driving adoption, they can also veil the true nature of the financial decisions inherent in these protocols. An examination of eBay’s market dynamics offers a clear parallel to the activities of DeFi liquidity providers, particularly in the context of market making and pawn brokering. The fundamental principles of buying low and selling high are universally applicable, transcending specific claims about the uniqueness of any given protocol, regardless of its tokenomics.</p><p>The notion of ‘toxic flow’, frequently misunderstood or misapplied in the context of DeFi, is critically assessed. It is often cited as a rationale for losses in unfavorable trades or as a placeholder for a user’s misunderstanding of the pricing algorithm to which they are subscribed. In contrast, traditional market manipulations such as spoofing, layering, and insider trading represent genuinely toxic activities, though they are not typically the focus when ‘toxic flow’ is discussed within DeFi circles.</p><p>As the DeFi industry progresses, it becomes essential to engage with target audiences under the premise that they seek to remain informed and critical. Rapid and efficient user onboarding processes should not eclipse the responsibility of protocol developers to offer adequate resources for self-education to those of reasonable intelligence. The aim of this article is to demonstrate that the financial theories underpinning DeFi exchange primitives are straightforward enough that the lack of basic understanding among many users is somewhat inexplicable and we, the industry leaders, should have a plan to address that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e7a713148a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/the-2023-pre-christmas-playstation-5-blu-ray-edition-ebay-bonding-curve-79e7a713148a">The 2023 Pre-Christmas PlayStation 5 (Blu-Ray Edition) eBay Bonding Curve</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‘Bitcoin,’ the Original Indie Rage Game Phenomenon]]></title>
            <link>https://medium.com/carbondefi/bitcoin-the-original-indie-rage-game-phenomenon-ab17faeb754c?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab17faeb754c</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 23:07:09 GMT</pubDate>
            <atom:updated>2023-12-18T14:29:58.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JAFrz_niHEbJ8u8WDePiQ.jpeg" /></figure><p>I heard you have some BTC, and you are looking to scale-out this cycle. Oh, you have never heard the term “scale-out”? It basically means you are done hodling your bags and plan to flip them into a <a href="https://koinly.io/au/">tax obligation</a> as the market rallies to the upside.</p><p>The premise is simple: set your bidding (or asking) price, and the number units you are willing to trade with. Think Bitcoin is going to $600,000? Why wait — throw it up on the order book with a $600,000 price tag and when the market is ready, <a href="https://x.com/saylor/status/1730226879125160426?s=20">Mike Saylor will buy it from you</a>.</p><p>But what if BTC doesn’t make it to $600,000? What if the market careers up to $590,000 and stalls? Surely it is going to top out at least near $500,000, right? Right? […] Maybe you aren’t sure. Alice in accounting said that she doesn’t expect Bitcoin to go much further than $200,000 this cycle. And you heard her friend, Bob, thinks that it will get rejected off the $70,000 level, forming a macro “double top”, whatever that is.</p><p>Okay, let’s back up. You have collected a few bitcoins over the years, so think carefully about how you might want to take profits on them. Let’s put one of your Bitcoins up for sale for $600,000 (hopefully we get there). I guess it would be sad if Bob was right, and the market turned around at only $70,000 — but how upset are you going to be if you sold nothing there, and hodled your bag back down to $12,000? Maybe, sell one of your Bitcoins at $70,000? It’s up to you — but you should know that Bob lost it all shorting $DOGE. Are you really going to listen to that hack?</p><p>One Bitcoin left. Alice thinks $200,000 is reasonable, and her job is <em>literally counting money</em>; we should consider her opinion. Ok, so if all your price targets are met to the upside, you will sell:</p><pre>1 BTC @ $70,000<br>1 BTC @ $200,000<br>1 BTC @ $600,000<br>Total: 3 BTC @ $290,000 (average)</pre><p>That’s going to wreak havoc on your OCD. You know, if you bump up that first number just a little, you can get the total to be a much nicer looking, even $300,000?</p><pre>1 BTC @ $100,000<br>1 BTC @ $200,000<br>1 BTC @ $600,000<br>Total: 3 BTC @ $300,000 (average)</pre><p>Wait, does that mean you should just put all 3 BTC in the book at $300,000? I mean, you would get the same result overall, and you wouldn’t even need BTC to go to $600,000 anymore.</p><pre>1 BTC @ $300,000<br>1 BTC @ $300,000<br>1 BTC @ $300,000<br>Total: 3 BTC @ $300,000 (average)</pre><p>Ah, but now you won’t get anything unless BTC makes it all the way to $300,000. I guess that’s the risk you are taking, putting all your chips down at exactly one price point. We should think about systematizing this. For example, what if you put 1 BTC at $300,000, and 1 BTC 20% below, and 1 BTC 20% above?</p><pre>1 BTC @ $250,000<br>1 BTC @ $300,000 (i.e. $250,000 + 20%)<br>1 BTC @ $360,000 (i.e. $300,000 + 20%)<br>Total: 3 BTC @ $303,333.3333…. (average)</pre><p>That’s weird. The steps seem right: $250k -&gt; (+ 20%) -&gt; $300k -&gt; (+ 20%) -&gt; $360k, but the average price is $303k, not $300k (your OCD be damned). It’s like a different kind of average price. They should really give it <a href="https://en.wikipedia.org/wiki/Geometric_mean">its own name</a>.</p><p>Anyway, does this feel better? Would you be happy if you only got to sell 1 BTC at $250,000? What if the price only went to $299,999.99! Can you imagine! Just one more cent and you might have sold one more BTC at the top. If only you had more BTC — then you could put a bunch of orders in the book, instead of only three.</p><p>Oh! BTC is actually composed of <a href="https://bitcoin.stackexchange.com/questions/114/what-is-a-satoshi">100,000,000 satoshis</a>. So then, why don’t you split those BTC up and spread them out a little more? Then you don’t have to worry about missing the next price step so much. Something like:</p><pre>0.5 BTC @ $250,000<br>0.5 BTC @ $268,913 (i.e. $250,000 + 7.57%)<br>0.5 BTC @ $289,258 (i.e. $268,913 + 7.57%)<br>0.5 BTC @ $311,141 (i.e. $289,258 + 7.57%)<br>0.5 BTC @ $334,680 (i.e. $311,141 + 7.57%)<br>0.5 BTC @ $360,000 (i.e. $334,680 + 7.57%)<br>Total: 3 BTC @ $303,333.3333…. (average)</pre><p>So if BTC gets all the way to the target of $360,000, there is no difference — you still get an average price of $303k and change. At least now you will be better off if whales start dumping at $299,999.99, because you will have already sold half your BTC before then. But, wait a second. What if the market turns around at $268,912.99? Then you only get to sell 0.5 BTC. You could split it up further, I guess. After all, you have three hundred million satoshis. Potentially, you could set up three hundred million limit orders:</p><pre>0.00000001 BTC @ $250,000.000000000<br>0.00000001 BTC @ $250,000.000000304 (i.e. $250,000.000000000 + 0.0000000012%)<br>(Repeat this three hundred million times. I’ll wait.)<br>0.00000001 BTC @ $359,999.999562428 (i.e. $359,999.999124857 + 0.0000000012%)<br>0.00000001 BTC @ $360,000.000000000 (i.e. $359,999.999562428 + 0.0000000012%)<br>Total: 3 BTC @ $303,333.3333….</pre><p>Perfect! Now you won’t miss a beat. Try to be fast, though. If you can set up 1 order per second, it will only take you 9.5 years to get everything ready. I’m sure the BTC markets will wait for you. It’s a shame you are only using an antiquated blockchain and centralized exchanges. If you were autistic enough to be on Ethereum, you could set up exactly this in roughly the time it takes to quote Mike Saylor’s investment thesis, “buy Bitcoin”.</p><p>On <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> this is called a “range order” — it’s like an infinite number of limit orders. You just tell it the start ($250,000) and end ($360,000) prices and put your tokens up for sale. Yes, you’re right! It’s <em>exactly</em> like DDOSing eBay with hundreds of millions of Beanie Babies listings. Except <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> is built to handle continuous pricing — so while billions of limit orders would tank your t̶o̶t̶t̶e̶r̶i̶n̶g̶ booming centralized exchange, it is not a problem for DEXes. Although, occasionally a few dozen cartoon JPEGS of cats can <a href="https://www.bbc.com/news/technology-42237162">gridlock</a> the entire Ethereum network. Blockchains are weird.</p><p>Yes, you can modify your position on <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> very easily. When the market starts creeping up to your price targets, you can choose to keep moving them away forever and never sell anything. Or, you can panic after lunch with Bob and choose to sell everything right now at whatever price your favorite TA guy tweets about. You can take some out and keep hodling it, put more in, move the price range — all from a UI that even your zoomer offspring would find appealing.</p><p>You’ll be fine. Have fun with it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtrLFVOta0XNxwERj-fPwA.jpeg" /></figure><p><em>Hello! I’m the Moai Monitor, your digital guide here to distill complex ideas into clear insights below.</em></p><p>This article is a satirical and somewhat technical piece on cryptocurrency trading strategies, specifically focusing on Bitcoin (BTC). It uses humor and sarcasm to discuss the complexities and uncertainties of setting price targets for selling Bitcoin.</p><p>The article starts by discussing the concept of “scaling out” of a position, which means selling off assets (in this case, Bitcoin) in increments at different price points. It humorously references the unpredictability of Bitcoin’s price, poking fun at the wide range of predictions from different people.</p><p>The writer uses a hypothetical scenario where a Bitcoin holder sets various ambitious price targets ($70,000, $200,000, and $600,000) for selling their Bitcoins. This reflects the real dilemma faced by traders in setting realistic yet profitable price targets. The writer also plays with the idea of averaging the selling price and aligning it with a neat figure ($300,000) for the sake of satisfying one’s OCD (Obsessive-Compulsive Disorder). This part satirizes how traders might overthink or overcomplicate their strategies for psychological satisfaction.</p><p>The dilemma of setting trading targets, as illustrated in the article, is indeed a significant concept in the world of trading, particularly in the volatile and unpredictable cryptocurrency markets.</p><ul><li><strong>Predicting Market Movements:</strong> One of the core challenges in trading is the difficulty of accurately predicting market movements. Cryptocurrency markets, known for their high volatility, exacerbate this challenge. Setting trading targets requires a trader to anticipate future price levels, which is inherently uncertain.</li><li><strong>Balancing Greed and Fear:</strong> The article touches on the emotional aspects of trading — greed and fear. Traders often struggle with the decision of when to sell: too early, and they might miss out on potential gains (greed); too late, and they might lose their profits or even incur losses (fear). Setting and sticking to predetermined targets can help manage these emotions.</li><li><strong>Influence of External Opinions:</strong> The article humorously references opinions from ‘Alice in accounting’ and ‘Bob’, who have different, somewhat arbitrary predictions for Bitcoin’s price. This highlights how traders might be influenced by others’ opinions, which can be unreliable or biased, or may not be based on sound analysis. This highlights the importance of developing one’s own informed trading strategy rather than relying on hearsay or following the crowd.</li><li><strong>Complexity of Trading Strategies:</strong> The article also satirizes the complexity that can be involved in setting trading targets. While a sophisticated strategy can be beneficial, overcomplicating things can lead to analysis paralysis or errors in execution.</li><li><strong>Adaptability and Flexibility:</strong> The dynamic nature of the market means that traders need to be adaptable. However, constantly changing targets or strategies in reaction to market movements can be a double-edged sword — it can either lead to better outcomes or result in poor decision-making under pressure.</li><li><strong>Technological Tools and Platforms:</strong> The discussion about <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> and range orders points to the evolving technological tools available to traders. These tools can offer more sophisticated ways to set and execute trading strategies.</li></ul><p>The laddered order structure mentioned in the article is a geometric sequence, which accumulates a geometric average price as each order is executed. In finance and trading, a geometric sequence or progression is a sequence of numbers where each term after the first is found by multiplying the previous term by a fixed, non-zero number called the ratio. This concept is often used in trading strategies like the one described in the article.</p><ul><li><strong>Starting Point:</strong> The sequence begins with an initial selling price. In the article, this is $250,000 for 0.5 BTC.</li><li><strong>Fixed Ratio:</strong> Each subsequent selling price is determined by multiplying the previous price by a fixed ratio. The article suggests a 7.57% increase each time, which is the ratio in this case.</li><li><strong>Application in Orders:</strong> This leads to a series of orders placed at increasing prices. Each price is 7.57% higher than the last. For example, if the first order is at $250,000, the next would be $250,000 multiplied by 1.0757, and so on.</li><li><strong>Advantages in Trading:</strong> This strategy can be advantageous in markets with high volatility and unpredictability, like cryptocurrencies. By setting up a laddered, geometric sequence of sell orders, a trader can potentially capture profits at various levels as the price rises, without trying to predict a single ‘top’ price.</li><li><strong>Risk Management:</strong> Such a strategy also helps in risk management. By not committing to a single exit price, traders can mitigate the risk of missing out on potential gains if the price doesn’t reach their single target price. It also helps in systematically taking profits while still leaving room for upside potential.</li><li><strong>Geometric Sequence Formula:</strong> Mathematically, a geometric sequence is described by the formula:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KedKlKmJPxgX52xgSI6Y5g.png" /></figure><p>The article concludes with a mention of <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a>, the most recent product from Bancor, highlighting its capability to facilitate a laddered trading strategy efficiently. This part of the article points to the evolving landscape of blockchain trading products and the unique advantages of <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> over traditional centralized exchanges.</p><ul><li><strong>Range Orders:</strong> In traditional centralized exchanges, placing many orders (like a laddered strategy with many incremental steps) can be cumbersome and time-consuming. However, <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> is designed to handle such strategies more efficiently. It can automate the process, allowing for the placement of quasi-infinite orders across a range without the need to manually set each one. This feature allows traders to specify a start and end price for their orders, and the system automatically creates a series of orders within this range.</li><li><strong>Smart Contracts and Automation:</strong> <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> leverages blockchain technology and smart contracts. Smart contracts can automate the execution of trades based on predefined criteria, such as the laddered price points in a geometric sequence. This reduces the manual workload and potential for human error.</li><li><strong>Accessibility and Flexibility:</strong> <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> is more accessible and flexible compared to traditional exchanges; it offers a wider range of tools and customizable options for traders, catering to both novice and experienced users.</li><li><strong>Decentralization Benefits:</strong> Being decentralized, <a href="https://www.carbondefi.xyz/?utm_source=Medium&amp;utm_medium=MarksMedium&amp;utm_campaign=ScalingInOut">Carbon DeFi</a> is not controlled by any single entity, which can offer advantages in terms of reduced counterparty risk, potentially lower fees, and resistance to censorship.</li></ul><p><em>For further insights, see related discussions in our companion articles: </em><a href="https://medium.com/carbondefi/crypto-trading-101-scaling-in-and-out-16f2ef27373d">Crypto Trading 101: Scaling In and Out</a><em> and </em><a href="https://medium.com/@Jen_Here2DeFi/maximize-market-gains-scaling-in-and-out-30ea3a99c6b4">Maximize Market Gains: Scaling In and Out</a><em>. These pieces complement the themes explored here, offering extended analysis on cryptocurrency trading and risk management strategies.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab17faeb754c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/bitcoin-the-original-indie-rage-game-phenomenon-ab17faeb754c">‘Bitcoin,’ the Original Indie Rage Game Phenomenon</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Forbidden Sandwich: A Theory of MEV-resistant CFMM Transactions]]></title>
            <link>https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a582efd98c98</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[automatic-market-maker]]></category>
            <category><![CDATA[mev]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 06:46:11 GMT</pubDate>
            <atom:updated>2023-08-11T16:26:37.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*nRc4Fn2VT26KMfed-jxKuA.jpeg" /></figure><h3>Introduction</h3><p>In my last <a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">article</a> I presented the fundamentals of the sandwich attack, whereby an exploiter can siphon value away from a naïve token swap by constructing a series of transactions during block creation that flank that of their victim. The process occurs in three steps 1) front run the user’s trade, creating a modified liquidity pool state with an arbitrarily reduced-price quote with respect to the token the user is attempting to sell, 2) allow the user’s trade through at the reduced rate and 3) back run the prior two steps, returning the liquidity pool to a comparatively normal state. It was demonstrated that the overall process is financially indistinguishable from an effective theft by the attacker, followed by a significant swap fee hike on the liquidity pool prior to the swap of what is left of the user’s tokens. Should one wish it, the formulae presented there, including an OptimumSandwich python class, are fertile ground to continue with independent study. I concluded the article by challenging the reader to derive a mathematical description for an “un-sandwichable” trade. That is, to show algebraically that for any set of state variables and user inputs wherein a sandwich attack can be performed, there exists a similar set where the modification of at most one of those elements will render a sandwich attack impossible. The purpose of this article is to describe the “un-sandwichable” set.</p><p>The conventions used here are the same as those established previously; to differentiate the inputs and outputs belonging to the <strong>a</strong>ttacker and the <strong>u</strong>ser, I’ll continue to use the subscripts <strong>a</strong> and <strong>u</strong>, respectively. Additionally, <em>x</em> will consistently represent the token that is being sent to the liquidity pool by either the attacker or the user, while <em>y</em> will invariably represent the token that is being transferred from the liquidity pool to either the user or the attacker. The lowercase Greek letter <em>δ</em> represents the liquidity pool swap fee, and the uppercase form, Δ, denotes trade quantities. Assume <em>x</em>, <em>y</em>, <em>δ</em>, Δ<em>x</em>, Δ<em>y</em>, are always positive real numbers, with Δ<em>x</em> and Δ<em>y</em> being the quantities of tokens that are taken from- and added to the wallets of the user or attacker, respectively (implying they’re added to- and removed from the liquidity pool balances in a corresponding manner). The difference between the number of tokens received by the attacker from the back running trade, and the same token sent to the liquidity pool during the front running trade is denoted with the letter <em>Q</em>.</p><h3>Breaking the Sandwich Vending Machine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*fb-ioDmW1rh47H20VHntOQ.jpeg" /></figure><p>The critical piece of information in the prior <a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">article</a> is that the attacker’s profits, <em>Q</em>, is optimal at a precise front running trade quantity, Δ<em>x</em>ₐ, given the token reserve of the liquidity pool, <em>x</em>, its fee level, <em>δ</em>, and the quantity of tokens the user is attempting to swap, Δ<em>x</em>ᵤ. The optimal front running trade quantity, Δ<em>x</em>ₐ, can be expressed as one of the roots of a quartic polynomial. Whereas the prior focus was to determine the value of Δ<em>x</em>ₐ while treating the other variables as constants, the aim here is to determine the value for the other variables, <em>x</em>, <em>δ</em>, and Δ<em>x</em>ᵤ, when the attacker’s optimum front running trade is zero. In other words, what combination of the pool state and user inputs cause the attacker to decide to do nothing, and leave the user’s transaction alone? Compared to this article’s predecessor, these solutions are markedly easier to find. Take the previously defined quartic and set the indeterminate, Δ<em>x</em>ₐ, to zero. This causes all but the constant term (i.e. the <em>D</em> coefficient) to be eliminated (eqn1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9F3Or31m3uzfblpJkDCpQ.png" /></figure><p>While the <em>x</em> term is still quartic, two of its roots are trivial (refer to the factorization below), and the other two are the solutions to a relatively benign quadratic. The Δ<em>x</em>ᵤ and <em>δ</em> terms are both cubic, but again, one root is trivial and the other can be surmised from application of the quadratic formula. As before, I am only presenting the roots that are contextually relevant. That is, for the infimum <em>δ</em>: 0 &lt; <em>δ</em> &lt; 1, the supremum Δ<em>x</em>ᵤ: Δ<em>x</em>ᵤ &gt; 0, and the infimum <em>x</em>: <em>x</em> &gt; 0 where the attacker’s optimal front running trade is Δ<em>x</em>ₐ ≤ 0 (eqns 2–4). For the benefit of majority of the readership, the meaning of these expressions can be understood as follows:</p><ol><li>Given a constant product liquidity pool with a token reserve of <em>x</em> ETH, where the user has nominated to swap Δ<em>x</em>ᵤ ETH for the counterpart token, the <strong>minimum swap fee</strong> that nullifies all value of a sandwich attack is inf <em>δ</em> (eqn 2). Therefore, any <em>δ</em> ≥ inf <em>δ</em> will also make a sandwich attack impossible (figure 1).</li><li>Given a constant product liquidity pool with a token reserve of <em>x</em> ETH, and a swap fee of <em>δ</em>, the <strong>maximum amount of ETH</strong> the user can swap before exposing a sandwich attack opportunity is sup Δ<em>x</em>ᵤ (eqn 3). Therefore, any Δ<em>x</em>ᵤ ≤ sup Δ<em>x</em>ᵤ will also make a sandwich attack impossible (figure 2).</li><li>Given a constant product liquidity pool with a swap fee of <em>δ</em>, where the user has nominated to swap Δ<em>x</em>ᵤ ETH for the counterpart token, the <strong>minimum token reserve of ETH</strong> in the constant product liquidity pool required to nullify the sandwich attack is inf <em>x</em> (eqn 4). Therefore, any <em>x</em> ≥ inf <em>x</em> will also make a sandwich attack impossible (figure 3).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQYslJ3L_MUZ8A5-MkpO6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a8EnGREfpSxzJbW7J3VFA.png" /><figcaption><strong>Figure 1: Analysis of inf δ with respect to x and Δxᵤ.</strong> In the context of a constant product liquidity pool holding a token reserve of x ETH, when the user chooses to exchange Δxᵤ ETH for its counterpart token, the lowest swap fee that renders a sandwich attack valueless is represented by inf δ (eqn 2). Swap fees greater than or equal to inf δ safeguard against the possibility of a sandwich attack. The visualizations are a) a three-dimensional (3D) surface plot on the left, and b) a corresponding heatmap on the right.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9iJPff84E9d8RitUyvlUw.png" /><figcaption><strong>Figure 2: Analysis of sup Δxᵤ in relation to x and δ.</strong> Given a constant product liquidity pool with a token reserve of x ETH and a swap fee of δ, the maximum ETH amount the user can exchange without risking a sandwich attack is represented by sup Δxᵤ (eqn 3). Any Δxᵤ less than or equal to sup Δxᵤ ensures immunity from the sandwich attack. The visualizations are a) a three-dimensional (3D) surface plot on the left, and b) a corresponding heatmap on the right.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Db6Zlldwg3FMGIxqZWMFyw.png" /><figcaption><strong>Figure 3: Analysis of inf x in relation to δ and Δxᵤ. </strong>Within a constant product liquidity pool operating with a swap fee of δ, when the user opts to exchange Δxᵤ ETH for the associated counterpart token, the least token reserve of ETH required in the liquidity pool to neutralize the potential for a sandwich attack is depicted by inf x (eqn 4). Reserves of x greater than or equal to inf x ensure a sandwich attack is unfeasible. The inf x axis is presented using a log10 scale. The visualizations are a) a three-dimensional (3D) surface plot on the left, and b) a corresponding heatmap on the right.</figcaption></figure><p>Cursory examination of eqns 3 and 4 reveals an opportunity to reduce the x and Δ<em>x</em>ᵤ dimensions into a single variable, <em>r</em> = <em>x</em>/ Δ<em>x</em>ᵤ. This is an intuitive simplification; it is not the absolute size of the user’s trade, but its relative size compared to the token reserve of the liquidity of the pool that matters (eqn 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dp48LkNKBoMcRhuqG3V2rw.png" /></figure><p>The new minimum values that describe a sandwich attack-resistant trade, inf <em>δ</em> and inf <em>r</em> can then be defined (eqns 6 and 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCI78lrQkvX8b9slPy6Qqw.png" /></figure><p>The interrogation of the plot of inf <em>δ</em> versus <em>r</em> challenges my intuition (figure 4). It is obvious that for <em>x</em>, Δ<em>x</em>ᵤ ∈ ℝ+, the limit of <em>r</em> = ∞ as <em>x</em> → ∞, the limit of <em>r</em> = 0 as Δ<em>x</em>ᵤ → ∞, and the limit of <em>r</em> = 1 as Δ<em>x</em>ᵤ → <em>x</em>. From a geometric perspective <em>r</em> = 1 is the “middle” of the range, as 0 and ∞ are in some sense equidistant from the limit at Δ<em>x</em>ᵤ → <em>x</em>. Nothing surprising so far. The limits of inf <em>δ</em> are also trivial; the limit of inf <em>δ</em> = 0 as <em>r</em> → ∞, the limit of inf <em>δ</em> = 1 as <em>r</em> → 0, and the natural “middle” of the range is <em>δ</em> = ½. I expected these midpoints to coincide with each other, but they do not. The <em>r</em> value that corresponds to <em>δ</em> = ½ is <em>r</em> = 1/√3, and the <em>δ</em> value that corresponds to <em>r</em> = 1 is <em>δ</em> = (9 — √33)/8. There is nothing apparently useful in this fact; I raise it only for curiosity’s sake. However, the analysis continues to bear fruit. The function that defines inf <em>δ</em> also exhibits asymptotically limiting behavior. The inf <em>δ</em> function is asymptotically equivalent to 1 — √<em>r</em> as <em>r</em> becomes arbitrarily large. It is also asymptotically equivalent to 2/(2<em>r</em> + 3) as <em>r</em> becomes arbitrarily close to but greater than 0 (eqns 8 and 9). An interactive plot is provided for the reader’s convenience via <a href="https://www.desmos.com/calculator/z9xxi3hmir">desmos</a>. The former (eqn 8) has more practical significance, as we seldom expect a user to be attempting a swap with a token quantity exceeding that of the entire reserve of the pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZXZt6UZdOh_SK3uOp5NuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULA0aMBPDInNS9VkncWCdQ.png" /><figcaption><strong>Figure 4: Analysis of inf δ with respect to r, where r = x/Δxᵤ.</strong> In the context of a constant product liquidity pool holding a token reserve of x ETH, when the user chooses to exchange Δxᵤ ETH for its counterpart token, and where the quotient of x and Δxᵤ is denoted as r, the lowest swap fee that renders a sandwich attack valueless is represented by inf δ (eqn 6). Swap fees greater than or equal to inf δ safeguard against the possibility of a sandwich attack. The visualizations are log-scaled plots highlighting the relationship between r and inf δ and showcasing a) key intersection points corresponding to the heuristic midpoints of the function domain, and b) asymptotic approximation of inf δ.</figcaption></figure><h3>Synthesizing an Inedible Sandwich</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAa5rbAJaHlNrBf7xI4GnQ.jpeg" /></figure><p>For the sake of consistency, this demonstration will re-use the scenarios introduced in the “Expected Behavior” and “A Delicious Sandwich for One” sections from the preceding article, “<a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">The Optimum Sandwich: How to Exploit Blockchain Enthusiasts with Arbitrary Precision</a>”. Assume a liquidity pool exists with 500 ETH (<em>x</em>) and 1,000,000 USDC (<em>y</em>), representing a combined total value of approximately $2M USD, from which a market price of ETH near $2,000 can be inferred. Additionally, assume the pool fee level, <em>δ</em>, is fixed at 0.003 (i.e. 0.3%, or 30 basis points) in the standard case.</p><p>The intent of this section is to navigate through the revelations arising from the prior discourse. I must underscore, though, that our journey here is largely scholastic. My primary objective is to enhance the reader’s grasp of the principles elaborated above, as well as the prior article. Existing methods, such as the minReturn, which present reasonably adept solutions against sandwich attacks should not be overlooked. I promise a closer examination of the minReturn criterion in an upcoming piece. For now, let the scope of this section be limited to the concepts covered thus far. Humor me.</p><p>First, consider the case where the user elects to swap 20 ETH for USDC:</p><ol><li>The user observes a pool with 500.000000 ETH tokens, <em>x</em>, and 1000000.000000 USDC tokens, <em>y</em>, and a swap fee of 0.300000%, <em>δ</em>.</li><li>The user elects to swap 20.000000 ETH tokens, Δ<em>x</em>ᵤ, and expects to receive 38346.153846 USDC tokens, Δ<em>y</em>ᵤ.</li><li>First, the attacker front runs the user’s trade by swapping 681.367696 ETH tokens, Δ<em>x</em>ₐ, for 575031.461640 USDC tokens, Δ<em>y</em>ₐ.</li><li>Then, the user’s trade is allowed through; the user swaps 20.000000 ETH tokens, Δ<em>x</em>ᵤ, for 7053.521318 USDC tokens, Δ<em>y</em>ᵤ.</li><li>Finally, the attacker back runs both of the previous trades by swapping 575031.461640 USDC tokens, Δ<em>x</em>ₐ, for 693.644385 ETH tokens, Δ<em>y</em>ₐ.</li><li>Therefore, the attacker has extracted a total of 12.276689 ETH tokens, <em>Q</em>, from the user’s transaction.</li><li>The overall process is equivalent to the user giving away 12.276689 ETH tokens, <em>Q</em>, to the attacker, then swapping the remaining 7.723311 ETH tokens, Δ<em>x</em>ᵤ, with the pool.</li><li>In addition to the sacrificed ETH token quantity, <em>Q</em>, the pool fee also appears to be increased from 0.300000% to 53.630805%, <em>δ</em>* (i.e. 17776.934872% increase).</li><li>At the end of the process, the liquidity pool contains 507.723311 ETH tokens, <em>x</em>, and 992946.478682 USDC tokens, <em>y</em>.</li><li>The user’s losses are -81.605662% with respect to the expected outcome.</li><li>The maximum unattackable trade at a 0.300000% fee level is to swap 1.506781 ETH tokens, sup Δ<em>x</em>ᵤ, to receive 2995.493230 USDC tokens, Δ<em>y</em>ᵤ.</li><li>Alternatively, if the fee level was changed to 3.773612%, inf <em>δ</em>, the user could have swapped all 20.000000 ETH tokens, Δ<em>x</em>ᵤ, for 37010.149326 USDC tokens, Δ<em>y</em>ᵤ, with no risk of attack.</li><li>The adjusted fee level translates to a mere -3.484064% difference compared to the naive swap, and a +424.704579% difference compared to the attacked transaction.</li></ol><p>Even as the author of this analysis, I find myself continually astonished by the apparent falsidical paradox revealed by performing it. The illustration above shows that for a pool fee setting of 0.3%, the cost of executing a sandwich attack is sufficiently low to allow the exploiter to reduce the initial transaction value by an abhorrent 81% margin. However, <em>increasing</em> the pool fee from 0.300% to 3.774% (inf <em>δ</em> evaluated for <em>x</em> = 500, Δ<em>x</em>ᵤ = 20) makes the transaction worthless to the would-be exploiter, and the transaction value is <em>improved</em> for the user by 424.705% compared to its exploited alternative. The difference is colossal, beyond anything I would suspect one might be able to arrive at by guessing alone. This serves as an [unwelcome?] reminder that although heuristics and intuition play a significant part in developing a solid theoretical framework, there comes a point where the need to carry out a concrete calculation becomes unavoidable. The data above are tabulated in figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVb4PaD-2kJxXSbVbBREfQ.png" /><figcaption><strong>Figure 5: Tabulated results of the sandwich attack illustration.</strong> a) Details of the sandwich attack and b) the adjusted swap quantity or pool fee setting that would have prevented it from occurring.</figcaption></figure><p>The upper limit of a non-attackable token swap, sup Δ<em>x</em>ᵤ, might initially seem mundane. Both equation 3 and figure 2 provide a comprehensive understanding of how variables <em>x</em> and <em>δ</em> affect its value, and the subsequent financial implications appear straightforward. However, there’s more under the surface that warrants a closer look.</p><p>The variable fee technique, which uses a dynamic inf <em>δ</em> calculation, presents a puzzle. The above example, in light of an almost infinite range of user inputs, is incomplete. Referring to the fee curve in figure 4, notice that when <em>r</em> values are minuscule — meaning Δ<em>x</em>ᵤ greatly outnumbers the token’s liquidity pool reserve, <em>x</em> — the pool fee nears 100%. As <em>r</em> approaches zero, both the inf <em>δ</em> function and its asymptotic approximation tend to unity, as shown in equations 6 and 9.</p><p>Acknowledging these traits, one might argue that this mechanism can’t maintain user value for exceptionally large swap sizes, possibly even for just moderately large ones. When inf <em>δ</em> values verge on 100% for substantial swaps, it’s logical to deduce that tokens transferred from the liquidity pool to the user would dwindle to almost nothing. There seems to be a paradox: as Δ<em>x</em>ᵤ tends toward infinity, Δ<em>y</em>ᵤ gravitates towards zero. Yet, the same is true when Δ<em>x</em>ᵤ is virtually non-existent. Put simply, swapping an endless amount of ETH into the pool yields the same result as swapping almost nothing — virtually no return. However, as already demonstrated, there are specific Δ<em>x</em>ᵤ values that produce very reasonable outputs for Δ<em>y</em>ᵤ, suggesting there exists a certain amount of ETH that maximizes the USDC return under inf <em>δ</em>’s effect. This can be proven algebraically (eqns. 10–13).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R5rQn5Rn5HNovX21QxsJXg.png" /></figure><p>At first glance, the overarching swap function (eqn 10) appears more complex than what we’re traditionally accustomed to. Thankfully, the intricacies of implementation are irrelevant, given the exploratory nature of this exercise. The somewhat daunting partial derivative (eqn 11) simplifies when evaluated at Δ<em>x</em>ᵤ = 0 to the familiar [feeless] constant product AMM marginal price formula (eqn 12), as expected. The derivative also has an easily identifiable root at Δ<em>x</em>ᵤ = 2<em>x</em>. This marks the precise quantity of ETH one can swap to maximize the USDC received from the pool (i.e. the point at which an additional, infinitesimal amount of ETH fails to yield any additional USDC to the swapper).</p><p>The prior deduction primarily highlights the imprudence of swapping more than double the pool’s ETH reserve in a single move. However, its dynamics in relation to the sandwich attack has yet to be addressed. It’s vital to note that this method ensures an unprofitable venture for any would-be exploiter attempting a sandwich attack, but it doesn’t promise a superior amount of USDC for the user compared to if they had been sandwiched instead. The question then, is if there exists a point where preventing a sandwich attack is more costly than simply allowing one to happen.</p><p>To delve deeper and truly gauge the breadth of this method, I subjected it to <em>r</em> values as low as 0.001, translating to trade volumes up to 500 times the aggregate value of both token reserves in the pool. Imagine, for the sake of our prior example, executing a staggering $1 billion ETH trade into a pool whose contents are merely $2 million, divided evenly between ETH and USDC. This is the most extreme case presently under examination (figure 6).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qcS3vEit1o5yxL43l8ZIA.png" /><figcaption><strong>Figure 6: Analysis of Δyᵤ with respect to Δxᵤ employing the minimum sandwich-attack resistant pool fee inf δ.</strong> When a user opts to exchange Δxᵤ ETH for its counterpart token, the potential value obtained by the user, Δyᵤ<strong>,</strong> is represented under normal conditions when no sandwich attack is performed (white trace), when the optimal sandwich attack is performed (red trace) at the 0.3% fee level, and when the minimum sandwich attack-resistant pool fee, inf δ, is employed. All three conditions assume a liquidity pool reserve balance of 500 ETH. The visualizations are a) log-log-scaled, up to and including Δxᵤ inputs 500× the liquidity pool reserve balance of ETH (i.e. 500,000 ETH), and b) linear in both dimensions, up to and including Δxᵤ inputs equal to 1× the liquidity pool reserve balance of ETH (i.e. 500 ETH). The local maxima of the inf δ method (blue trace) and the sandwich-attacked trade (red trace), and the intersection point of these two curves are depicted with broken lines and labelled according to their x- and y-coordinates (Δxᵤ and Δyᵤ, respectively).</figcaption></figure><p>It is crucial to first acknowledge that employing inf <em>δ</em> in place of <em>δ</em> — aimed at averting a sandwich attack — enhances the user’s rate of value retention at an accelerating rate. This happens with an unexpected persistence as Δ<em>x</em>ᵤ values ascend, but only up to a point. The peak at Δ<em>x</em>ᵤ = 2<em>x</em>, deduced above (eqn 13), stands out clearly. A similar peak can be discerned for the sandwiched transaction curve, a feature not discussed previously. But the crux of our observation lies in the convergence of the blue and red traces. At this juncture, falling prey to a sandwich at a 0.03% fee matches the outcome of an anticipatory fee surge. For any swap exceeding this threshold, the irony is palpable: succumbing to a sandwich attack becomes more economical than its prevention.</p><p>Unfortunately, if it is possible to describe the local maxima around the red trace, or its intersection point with the blue trace algebraically, it is beyond my abilities at present. I suspect it may be impossible, but I can’t be sure without committing more time to this question than it is worth. I’ll offer a 100 USDC bounty to the first person that can provide a purely symbolic solution to this problem, or proof that one can’t exist. The red trace maxima (Δ<em>x</em>ᵤ = 49,518.49922993397 ETH, Δ<em>y</em>ᵤ = 57,986.60716050453 USDC) and the red-blue trace intersection (Δ<em>x</em>ᵤ = 181,608.08402209895 ETH, Δ<em>y</em>ᵤ = 50,907.34540591974 USDC) were determined numerically.</p><p>This analysis considers only the situation where both the user and the attacker observe the same pool fee level, either the de facto 0.3% in the case of emulating a sandwiched trade, or whatever the calculated inf <em>δ</em> value is, appropriate to nullify the attack. While the variable fee technique used here is referred to as “dynamic”, it should be stressed that this refers to the model itself, and not a hypothetical CFMM design. While the dynamics of an “on-the-fly” fee calculation, and especially its impact on sandwich MEV is interesting enough to warrant further investigation, that deep dive remains outside the purview of the present discussion.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7Mm2tcwbEDScsdLF1kB0g.jpeg" /></figure><p>The theory presented here is motivated by a desire for a more robust analytical foundation for describing sandwich attacks in relation to arbitrary fee levels, liquidity depth, and user transaction sizes. Nothing presented here should be conflated with the fundamentals of CFMM design, necessarily. As noted above, the minReturn is a perfectly serviceable answer to the challenge of sandwich attack mitigation and will be the focus of a future analysis. Instead, let the distribution of value between the pool’s liquidity providers, its swapper, and his adversary be the subject of your attention. If nothing else, these models cast new light on an old problem, and illuminates the previously uncharacterized, bounded nature of the industry’s most popular exploit.</p><h4>Postscript</h4><p>This piece emerges alongside <a href="https://medium.com/@odtorson">Stefan Loesch’</a>s recent exploration into how <a href="http://www.carbondefi.xyz/"><em>Carbon</em></a>, Bancor’s trading protocol, <a href="https://medium.com/carbondefi/carbon-the-mev-sandwich-is-toast-2ec7800dde68">stands up to sandwich attacks</a>. Loesch delves into the practicality of these attacks, and comments specifically on their practicability under different fee structures. His insights corroborate the findings presented in the present analysis.</p><h4>Updated Code Block: OptimumSandwich Class (python)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eD6rFrfna_Qs6ugauDM88A.jpeg" /></figure><p>The OptimumSandwich class (below) is updated from that in the prior publication, and outputs the bulleted text from the previous section, and the tabulated data in figure 5 to a text file.</p><pre>class OptimumSandwich:<br>    def __init__(<br>        self,<br>        x: Decimal = Decimal(&#39;500&#39;), # the {x_ticker} token balance of the constant product liquidity pool.<br>        y: Decimal = Decimal(&#39;1_000_000&#39;), # the {y_ticker} token balance of the constant product liquidity pool.<br>        d: Decimal = Decimal(&#39;0.003&#39;), # the fee level (decimal, 0.003 = 0.3% = 30 bps) of the constant product liquidity pool.<br>        Dx_u: Decimal = Decimal(&#39;20&#39;), # the number of {x_ticker} tokens elected by the user to swap with the pool for {y_ticker} tokens.<br>        print_analysis: bool = False, # prints a bulleted list and tabulated summary of the class.<br>        x_ticker: str = &#39;ETH&#39;,<br>        y_ticker: str = &#39;USDC&#39;<br>        ):<br>        self.x = x<br>        self.y = y<br>        self.d = d<br>        self.Dx_u = Dx_u<br>        self.A = self.calculate_coefficient_A()<br>        self.B = self.calculate_coefficient_B()<br>        self.C = self.calculate_coefficient_C()<br>        self.D = self.calculate_coefficient_D()<br>        self.gamma = self.calculate_gamma()<br>        self.nu = self.calculate_nu()<br>        self.omega = self.calculate_omega()<br>        self.phi = self.calculate_phi()<br>        self.tau = self.calculate_tau()<br>        self.mu = self.calculate_mu()<br>        self.eta = self.calculate_eta()<br>        self.rho = self.calculate_rho()<br>        self.beta = self.calculate_beta()<br>        self.alpha = self.calculate_alpha()<br>        self.Dx_a = self.calculate_Dx_a()<br>        self.Dy_a = self.calculate_Dy_expected(self.Dx_a, self.d)<br>        self.Q = self.calculate_Q()<br>        self.Dy_u_expected = self.calculate_Dy_expected(self.Dx_u, self.d)<br>        self.Dy_u_obtained = self.calculate_Dy_u_obtained()<br>        self.d_u = self.calculate_d_u()<br>        self.sup_Dx_u = self.calculate_sup_Dx_u()<br>        self.Dy_u_sup_Dx_u = self.calculate_Dy_expected(self.sup_Dx_u, self.d)<br>        self.inf_d = self.calculate_inf_d()<br>        self.Dy_u_inf_d = self.calculate_Dy_expected(self.Dx_u, self.inf_d)<br>        if print_analysis:<br>            self.print_analysis(x_ticker, y_ticker)<br>        <br>    def calculate_coefficient_A(self):<br>        return(<br>            + Decimal(&#39;2&#39;)*self.d*(<br>                + Decimal(&#39;2&#39;) <br>                - self.d<br>            )*(<br>                + self.Dx_u*(<br>                    + self.d <br>                    + (<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )**Decimal(&#39;2&#39;)<br>                ) <br>                + Decimal(&#39;2&#39;)*self.x<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_coefficient_B(self):<br>        return(<br>            + (<br>                + self.d*(<br>                    + self.Dx_u*(<br>                        + self.Dx_u <br>                        + Decimal(&#39;6&#39;)*self.x<br>                        - (<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )*(<br>                            + self.Dx_u <br>                            - (<br>                                + Decimal(&#39;1&#39;) <br>                                - self.d<br>                            )**Decimal(&#39;2&#39;)*(<br>                                + Decimal(&#39;2&#39;)*self.x<br>                                + self.Dx_u <br>                            )<br>                            + (<br>                                + Decimal(&#39;1&#39;) <br>                                - self.d<br>                            )*(<br>                                + Decimal(&#39;3&#39;)*self.x <br>                                - self.Dx_u<br>                            ) <br>                        )<br>                    ) <br>                    + Decimal(&#39;6&#39;)*self.x**Decimal(&#39;2&#39;)*(<br>                        + Decimal(&#39;2&#39;) <br>                        - self.d<br>                    )<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>    <br>    def calculate_coefficient_C(self):<br>        return(<br>            + (<br>                + Decimal(&#39;2&#39;)*self.x*(<br>                    + self.x<br>                    + self.d*self.Dx_u <br>                )*(<br>                    + self.Dx_u*(<br>                        + (<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )**Decimal(&#39;2&#39;) <br>                        - self.d<br>                    ) <br>                    - Decimal(&#39;2&#39;)*self.d*self.x*(<br>                        + Decimal(&#39;2&#39;) <br>                        - self.d<br>                    )<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br><br>    def calculate_coefficient_D(self):<br>        return(<br>            + self.x*(<br>                + self.x <br>                + self.d*self.Dx_u<br>            )*(<br>                + (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)*(<br>                    + self.x <br>                    + self.Dx_u<br>                )**Decimal(&#39;2&#39;) <br>                - self.x*(<br>                    + self.x <br>                    + self.d*self.Dx_u<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_gamma(self):<br>        return(<br>            + (<br>                + self.B<br>                - (<br>                    + (<br>                        + Decimal(&#39;3&#39;)*self.A**Decimal(&#39;2&#39;)/Decimal(&#39;8&#39;)<br>                    )<br>                )<br>            )/Decimal(&#39;6&#39;)<br>        )<br>        <br>    def calculate_nu(self):<br>        return(<br>            + (<br>                + self.A*self.C/Decimal(&#39;4&#39;)<br>            )<br>        )<br>        <br>    def calculate_omega(self):  <br>        return(<br>            + self.gamma*(<br>                + self.nu<br>                + self.B*(<br>                    self.A/Decimal(&#39;4&#39;)<br>                )**Decimal(&#39;2&#39;)<br>                - Decimal(&#39;3&#39;)*(<br>                    + self.A/Decimal(&#39;4&#39;)<br>                )**Decimal(&#39;4&#39;)<br>                - self.D<br>            )<br>        )<br>        <br>    def calculate_phi(self):<br>        return(<br>            + (<br>                + (<br>                    + (<br>                        + self.A/Decimal(&#39;2&#39;)<br>                    )**Decimal(&#39;3&#39;) <br>                    - (<br>                        + self.A*self.B<br>                    )/Decimal(&#39;2&#39;) <br>                    - self.C<br>                )/Decimal(&#39;4&#39;)<br>            )**Decimal(&#39;2&#39;)<br>        )<br>        <br>    def calculate_tau(self):<br>        return(<br>            + self.D <br>            - self.A*self.C/Decimal(&#39;4&#39;) <br>            - self.B**Decimal(&#39;2&#39;)/Decimal(&#39;12&#39;)<br>        )<br>    <br>    def calculate_mu(self):<br>        return(<br>            + (<br>                + (<br>                    + (<br>                        + self.tau<br>                    )/Decimal(&#39;3&#39;) <br>                )**Decimal(&#39;3&#39;)<br>                + (<br>                    + (<br>                        + self.omega <br>                        - self.phi<br>                        - self.gamma**Decimal(&#39;3&#39;)<br>                    )**Decimal(&#39;2&#39;)<br>                )<br>            )**(<br>            + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br><br>    def calculate_eta(self):<br>        return(<br>            + (<br>                + self.mu <br>                + self.gamma**Decimal(&#39;3&#39;)<br>                + self.phi<br>                - self.omega<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;3&#39;)<br>            )<br>        )<br>        <br>    def calculate_rho(self):<br>        return(<br>            + Decimal(&#39;2&#39;)*self.tau/(<br>                + Decimal(&#39;3&#39;)*self.eta<br>            )<br>        )<br>        <br>    def calculate_beta(self):<br>        return(<br>            + (<br>                + (<br>                    + self.A/Decimal(&#39;2&#39;)<br>                )**Decimal(&#39;2&#39;) <br>                - (<br>                    + Decimal(&#39;2&#39;)*self.B<br>                )/Decimal(&#39;3&#39;) <br>                - self.rho <br>                + Decimal(&#39;2&#39;)*self.eta<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_alpha(self):<br>        return(<br>            + (<br>                + self.A**Decimal(&#39;2&#39;)/Decimal(&#39;2&#39;) <br>                - (<br>                    + Decimal(&#39;4&#39;)*self.B<br>                )/Decimal(&#39;3&#39;) <br>                - (<br>                    + self.A**Decimal(&#39;3&#39;)/Decimal(&#39;4&#39;) <br>                    - self.A*self.B <br>                    - Decimal(&#39;2&#39;)*self.C<br>                )/self.beta <br>                - Decimal(&#39;2&#39;)*self.eta <br>                + self.rho<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_Dx_a(self):<br>        return(<br>            + (<br>                + self.alpha <br>                + self.beta<br>            )/Decimal(&#39;2&#39;) <br>            - self.A/Decimal(&#39;4&#39;)<br>        )<br>        <br>    def calculate_Q(self):<br>        return(<br>            + (<br>                + self.Dx_a*(<br>                    + self.Dx_u*(<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )*(<br>                        + self.Dx_a <br>                        + self.x <br>                        - self.Dx_a*(<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )<br>                    ) <br>                    - (<br>                        + self.Dx_a <br>                        + self.x<br>                    )*(<br>                        + self.Dx_a <br>                        + self.Dx_u <br>                        + self.x<br>                    ) <br>                    + (<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )**Decimal(&#39;2&#39;)*(<br>                        + self.Dx_a <br>                        + self.Dx_u <br>                        + self.x<br>                    )**Decimal(&#39;2&#39;)<br>                )<br>            )/(<br>                + self.Dx_u*(<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )*(<br>                    + self.Dx_a*(<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    ) <br>                    - self.Dx_a <br>                    - self.x<br>                ) <br>                + (<br>                    + self.Dx_a <br>                    + self.x<br>                )*(<br>                    + self.Dx_a <br>                    + self.Dx_u <br>                    + self.x<br>                )<br>            )<br>        )<br>        <br>    def calculate_Dy_expected(self, Dx, d):<br>        return(<br>            + Dx*self.y*(<br>                + Decimal(&#39;1&#39;)<br>                - d<br>                )/(<br>                + self.x<br>                + Dx<br>            )<br>        )<br>    <br>    def calculate_Dy_u_obtained(self):<br>        return(<br>            + self.Dx_u*self.y*(<br>                + Decimal(&#39;1&#39;) <br>                - self.d<br>            )*(<br>                + self.Dx_a*self.d <br>                + self.x<br>            )/(<br>                + (<br>                    + self.Dx_a <br>                    + self.x<br>                )*(<br>                    + self.Dx_a <br>                    + self.Dx_u <br>                    + self.x<br>                )<br>            )<br>        )<br>        <br>    def calculate_d_u(self):<br>        return(<br>            + Decimal(&#39;1&#39;)<br>            - self.Dy_u_obtained/self.y <br>            - self.Dy_u_obtained*self.x/(<br>                + (<br>                    + self.Dx_u<br>                    - self.Q<br>                )*self.y<br>            )<br>        )<br>        <br>    def calculate_sup_Dx_u(self):<br>        return(<br>            + self.x*(<br>                + self.d*(<br>                    + Decimal(&#39;5&#39;) <br>                    - Decimal(&#39;2&#39;)*self.d<br>                ) <br>                + (<br>                    + (<br>                        + Decimal(&#39;2&#39;) <br>                        - self.d<br>                    )*(<br>                        + Decimal(&#39;2&#39;) <br>                        + Decimal(&#39;4&#39;)*self.d**Decimal(&#39;2&#39;) <br>                        - Decimal(&#39;5&#39;)*self.d<br>                    )<br>                )**(<br>                    + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>                ) <br>                - Decimal(&#39;2&#39;)<br>            )/(<br>                + Decimal(&#39;2&#39;)*(<br>                    + self.d <br>                    - Decimal(&#39;1&#39;)<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_inf_d(self):<br>        return(<br>            + (<br>                + (<br>                    + self.Dx_u <br>                    + Decimal(&#39;2&#39;)*self.x<br>                )*(<br>                    + Decimal(&#39;2&#39;)*self.Dx_u <br>                    + self.x<br>                ) <br>                - (<br>                    + self.x*(<br>                        + self.Dx_u <br>                        + Decimal(&#39;2&#39;)*self.x<br>                    )*(<br>                        + Decimal(&#39;4&#39;)*self.Dx_u**Decimal(&#39;2&#39;) <br>                        + Decimal(&#39;5&#39;)*self.Dx_u*self.x <br>                        + Decimal(&#39;2&#39;)*self.x**Decimal(&#39;2&#39;)<br>                    )<br>                )**(<br>                    + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>                )<br>            )/(<br>                + Decimal(&#39;2&#39;)*(<br>                    + self.Dx_u <br>                    + self.x<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def print_analysis_tables(self, f, x_ticker, y_ticker):<br>        table_1_data = [<br>            [f&quot;{x_ticker} tokens in pool&quot;, f&quot;{self.x:.6f}&quot;],<br>            [f&quot;{y_ticker} tokens in pool&quot;, f&quot;{self.y:.6f}&quot;],<br>            [f&quot;Swap fee (%)&quot;, f&quot;{(self.d*100):.6f}&quot;],<br>            [f&quot;User&#39;s {x_ticker} tokens to swap&quot;, f&quot;{self.Dx_u:.6f}&quot;],<br>            [f&quot;User&#39;s expected {y_ticker} tokens in return&quot;, f&quot;{self.Dy_u_expected:.6f}&quot;]<br>        ]<br>        <br>        table_2_data = [<br>            [f&quot;Attacker&#39;s front running {x_ticker} tokens swapped&quot;, f&quot;{self.Dx_a:.6f}&quot;],<br>            [f&quot;{y_ticker} tokens received by attacker&quot;, f&quot;{self.Dy_a:.6f}&quot;],<br>            [f&quot;User&#39;s {x_ticker} tokens swapped&quot;, f&quot;{self.Dx_u:.6f}&quot;],<br>            [f&quot;{y_ticker} tokens received by user&quot;, f&quot;{self.Dy_u_obtained:.6f}&quot;]<br>        ]<br><br>        table_3_data = [<br>            [f&quot;{y_ticker} tokens attacker swaps back&quot;, f&quot;{self.Dy_a:.6f}&quot;],<br>            [f&quot;{x_ticker} tokens attacker ends up with&quot;, f&quot;{(self.Dx_a + self.Q):.6f}&quot;],<br>            [f&quot;{x_ticker} tokens extracted from user&#39;s transaction&quot;, f&quot;{self.Q:.6f}&quot;]<br>        ]<br><br>        table_4_data = [<br>            [f&quot;Pool&#39;s final {x_ticker} tokens&quot;, f&quot;{(self.x + self.Dx_u - self.Q):.6f}&quot;],<br>            [f&quot;Pool&#39;s final {y_ticker} tokens&quot;, f&quot;{(self.y - self.Dy_u_obtained):.6f}&quot;],<br>            [f&quot;User&#39;s losses (%)&quot;, f&quot;{-(Decimal(&#39;1&#39;) - self.Dy_u_obtained/self.Dy_u_expected)*100:.6f}&quot;],<br>            [f&quot;New effective pool fee (%)&quot;, f&quot;{self.d_u*100:.6f}&quot;],<br>            [f&quot;Pool fee increase (%)&quot;, f&quot;{100*(self.d_u/self.d - 1):.6f}&quot;]<br>        ]<br><br>        table_5_data = [<br>            [f&quot;Maximum unattackable {x_ticker} tokens to swap&quot;, f&quot;{self.sup_Dx_u:.6f}&quot;],<br>            [f&quot;{y_ticker} tokens user would receive&quot;, f&quot;{self.Dy_u_sup_Dx_u:.6f}&quot;],<br>            [f&quot;New fee level for unattackable trade (%)&quot;, f&quot;{self.inf_d*100:.6f}&quot;],<br>            [f&quot;{y_ticker} tokens user would receive at new fee&quot;, f&quot;{self.Dy_u_inf_d:.6f}&quot;],<br>            [f&quot;Difference compared to naive swap (%)&quot;, f&quot;{(-(self.Dy_u_expected - self.Dy_u_inf_d)/self.Dy_u_expected*100):.6f}&quot;],<br>            [f&quot;Difference compared to attacked transaction (%)&quot;, f&quot;{((self.Dy_u_inf_d - self.Dy_u_obtained)/self.Dy_u_obtained*100):.6f}&quot;]<br>        ]<br><br>        f.write(&quot;\n&quot;)<br>        f.write(&quot;Initial Pool State and User&#39;s Trade Decision\n&quot;)<br>        f.write(tabulate(table_1_data, headers=[&quot;Description&quot;, &quot;Value&quot;], tablefmt=&#39;pretty&#39;) + &quot;\n&quot;)<br>        f.write(&quot;\nAttacker&#39;s Trade and User&#39;s Actual Trade Result\n&quot;)<br>        f.write(tabulate(table_2_data, headers=[&quot;Description&quot;, &quot;Value&quot;], tablefmt=&#39;pretty&#39;) + &quot;\n&quot;)<br>        f.write(&quot;\nAttacker&#39;s Back Running and Extraction Result\n&quot;)<br>        f.write(tabulate(table_3_data, headers=[&quot;Description&quot;, &quot;Value&quot;], tablefmt=&#39;pretty&#39;) + &quot;\n&quot;)<br>        f.write(&quot;\nSummary of User&#39;s Losses and Pool&#39;s Final State\n&quot;)<br>        f.write(tabulate(table_4_data, headers=[&quot;Description&quot;, &quot;Value&quot;], tablefmt=&#39;pretty&#39;) + &quot;\n&quot;)<br>        f.write(&quot;\nUnattackable Trade and Adjusted Fee Level\n&quot;)<br>        f.write(tabulate(table_5_data, headers=[&quot;Description&quot;, &quot;Value&quot;], tablefmt=&#39;pretty&#39;) + &quot;\n&quot;)<br>        return None<br>        <br>    def print_analysis(self, x_ticker, y_ticker):<br>        with open(&#39;sandwich_analysis.txt&#39;, &#39;w&#39;) as f:<br>            f.write(f&quot;1. The user observes a pool with {self.x:.6f} {x_ticker} tokens and {self.y:.6f} {y_ticker} tokens, and a swap fee of {(self.d*100):.6f}%.\n&quot;)<br>            f.write(f&quot;2. The user elects to swap {self.Dx_u:.6f} {x_ticker} tokens and expects to receive {self.Dy_u_expected:.6f} {y_ticker} tokens.\n&quot;)<br>            if self.Dx_a &gt; Decimal(&#39;0&#39;):<br>                f.write(f&quot;3. First, the attacker front runs the user&#39;s trade by swapping {self.Dx_a:.6f} {x_ticker} tokens for {self.Dy_a:.6f} {y_ticker} tokens.\n&quot;)<br>                f.write(f&quot;4. Then, the user&#39;s trade is allowed through; the user swaps {self.Dx_u:.6f} {x_ticker} tokens for {self.Dy_u_obtained:.6f} {y_ticker} tokens.\n&quot;)<br>                f.write(f&quot;5. Finally, the attacker back runs both of the previous trades by swapping {self.Dy_a:.6f} {y_ticker} tokens for {(self.Dx_a + self.Q):.6f} {x_ticker} tokens.\n&quot;)<br>                f.write(f&quot;6. Therefore, the attacker has extracted a total of {self.Q:.6f} {x_ticker} tokens from the user&#39;s transaction.\n&quot;)<br>                f.write(f&quot;7. The overall process is equivalent to the user giving away {self.Q:.6f} {x_ticker} tokens to the attacker, then swapping the remaining {(self.Dx_u - self.Q):.6f} {x_ticker} tokens with the pool.\n&quot;)<br>                f.write(f&quot;8. In addition to the sacrificed {x_ticker} token quantity, the pool fee also appears to be increased from {(self.d*100):.6f}% to {(self.d_u*100):.6f}% (i.e. {100*(self.d_u/self.d - 1):.6f}% increase).\n&quot;)<br>                f.write(f&quot;9. At the end of the process, the liquidity pool contains {(self.x + self.Dx_u - self.Q):.6f} {x_ticker} tokens, and {(self.y - self.Dy_u_obtained):.6f} {y_ticker} tokens.\n&quot;)<br>                f.write(f&quot;10. The user&#39;s losses are -{(Decimal(&#39;1&#39;) - self.Dy_u_obtained/self.Dy_u_expected)*100:.6f}% with respect to the expected outcome.\n&quot;)<br>                f.write(f&quot;11. The maximum unattackable trade at a {(self.d*100):.6f}% fee level is to swap {self.sup_Dx_u:.6f} {x_ticker} tokens to receive {self.Dy_u_sup_Dx_u:.6f} {y_ticker} tokens.\n&quot;)<br>                f.write(f&quot;12. Alternatively, if the fee level was changed to {(self.inf_d*100):.6f}%, the user could have swapped all {self.Dx_u:.6f} {x_ticker} tokens for {self.Dy_u_inf_d:.6f} {y_ticker} tokens with no risk of attack.\n&quot;)<br>                f.write(f&quot;13. The adjusted fee level translates to a mere -{((self.Dy_u_expected - self.Dy_u_inf_d)/self.Dy_u_expected*100):.6f}% difference compared to the naive swap, and a +{((self.Dy_u_inf_d - self.Dy_u_obtained)/self.Dy_u_obtained*100):.6f}% difference compared to the attacked transaction.\n&quot;)<br>                self.print_analysis_tables(f, x_ticker, y_ticker)<br>            else:<br>                f.write(&#39;3. Any attempted sandwich attack on this trade will not benefit the exploiter in any way.&#39;)<br>        return None</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a582efd98c98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/the-forbidden-sandwich-a-theory-of-mev-resistant-cfmm-transactions-a582efd98c98">The Forbidden Sandwich: A Theory of MEV-resistant CFMM Transactions</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Optimum Sandwich: How to Exploit Blockchain Enthusiasts with Arbitrary Precision]]></title>
            <link>https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5?source=rss-dc6f0052b77e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9131a2562b5</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[mev]]></category>
            <category><![CDATA[automatic-market-maker]]></category>
            <category><![CDATA[defi]]></category>
            <dc:creator><![CDATA[Mark Richardson]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 00:18:27 GMT</pubDate>
            <atom:updated>2023-08-10T12:49:39.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yvtk5KJuKATfbZy68YX0OA.png" /></figure><h3>Introduction</h3><p>I often have opportunity to discuss various aspects of our industry with a studious and enthusiastic audience. Anecdotally, sandwich attacks are among the more frequently requested discussion topics. I suspect the interest in this specific attack vector is owed to its ominous and threatening nature. Indeed, sandwich attacks are one of the more credible fears shared by the DeFi community; however, it is remarkable how few of its members can articulate exactly what a sandwich attack is, let alone derive the equations that describe how one is performed. I am forced to concede that I must shoulder at least part of the blame for the disappointing levels of erudition exhibited by the typical DeFi pedestrian. Experience demonstrates that I have failed to guide an otherwise capable and willing audience to the understanding they have politely asked for, and rightfully deserve. My resolve is to expose here the full itinerary for performing a sandwich attack, and the mathematical methods that allow for the industry’s top exploiters to wring dry every available wei of value (quite literally) from vulnerable trades. Under any other circumstance there may be a reasonable question of ethics with respect to publishing information that is so easily weaponizable. Unfortunately for us, those who would seek to weaponize it, have already, and so I see no adverse consequences to emptying the black boxes of our adversaries and exploring their contents together.</p><h3>Expected Behavior</h3><p>At the risk of sounding naïve, I want to begin by examining the prototypical case where a user trades against a generic constant product liquidity pool and expects to be delivered the tokens they surmised from the algorithms employed in the smart contracts with which they are interacting. That is, the result of the familiar swap function (eqn 1). To distinguish between inputs and outputs associated with the <strong>a</strong>ttacker and the <strong>u</strong>ser, I will use the subscripts <strong>a</strong> and <strong>u</strong>, respectively. Further, let <em>x</em> always denote the token that is being sent to the liquidity pool from either the attacker or the user, and let <em>y</em> always denote the token that is being sent from the liquidity pool to either the attacker or the user. I will also observe the old convention of denoting the liquidity pool swap fee with the lowercase Greek letter <em>δ</em>, and trade amounts with the uppercase form, Δ. Assume <em>x</em>, <em>y</em>, <em>δ</em>, Δ<em>x</em>, Δ<em>y</em>, are always positive real numbers, where Δ<em>x</em> and Δ<em>y</em> are quantities of tokens subtracted from- and added to the user or attacker wallets, respectively (and by inference, added to- and subtracted from the liquidity pool balances, respectively).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmrqJ-dkKMV-9Ml78Ih3CA.png" /></figure><p>Assume a liquidity pool exists with 500 ETH and 1,000,000 USDC, representing a combined total value of approximately $2M USD, from which a market price of ETH near $2,000 can be inferred. For convenience, assume the pool fee level, <em>δ</em>, is fixed at 0.003 (i.e. 0.3%, or 30 basis points). Then, assume that a user is motivated to swap 20 ETH (i.e. ~$40K nominal value) with the pool. The expected result after the effect of price slippage and after accounting for the trading fee is summarized in figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eF6w7jUZcZ9l0hUO49kBhg.png" /><figcaption><strong>Figure 1: The (naïve) expected result.</strong> 20 ETH is exchanged for 38,346.1538 USDC from a constant product liquidity pool comprising 500 ETH and 1,000,000 USDC, and near $2M USD total liquidity.</figcaption></figure><p>What is depicted above is the desired outcome, if we allow ourselves the dubious assumption that the user is familiar with the basics of constant-function market making (CFMM).</p><h3>A Delicious Sandwich for One</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gsr6HKtev96RcbLHlFLf4A.jpeg" /></figure><p>Armed with only a modest working knowledge of the CFMM algorithm and the requisite skills for its algebraic manipulation, and perhaps a reckless disregard for the wellbeing of the user, it is possible to intervene in the expected process and siphon significant value away from the transaction and into your own wallet. Before I provide the instructions for performing such an attack under arbitrary conditions, I first want to demonstrate the attack using the expected behavior depicted in figure 1 as an example specimen.</p><h4>Step 1: Front Run the Trade</h4><p>After observing the user’s transaction in the mempool, the attacker can very quickly calculate a precise number of tokens to trade ahead of the user’s expected swap to maximize the effectiveness of the exploit. For now, take me at my word that the most efficient exploit is to front run the user’s 20 ETH trade with a swap in the same direction for 575,031.4616 USDC (figure 2). To the uninitiated, this may seem like a rather impulsive act. It has often been my experience that newcomers to DeFi, and especially those without prior knowledge in CeFi, are under the misapprehension that front running is akin to being beaten to an attractive price by another participant who is equally, if not more interested in the purchase of the same token as they are. Let me put that fantasy to rest. Save for a vanishing minority of cases, the person front running you has absolutely no interest in the token you are attempting to purchase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nujNSzIrrAwjQ9pZEaz0Eg.png" /><figcaption><strong>Figure 2: Step 1 — Front run the trade.</strong> The attacker performs a large trade in the same direction as the user and makes certain that their swap is ahead of the user’s in the transaction sequence; 681.3677 ETH is swapped by the attacker for 575,031.4616 USDC.</figcaption></figure><h4>Step 2: Allow the User’s Swap to Proceed on the Rigged Liquidity Pool</h4><p>With the prices inside the liquidity pool now appropriately adjusted to set the stage for the exploit, it is now critical that the user’s swap transaction is executed immediately following the front run (figure 3). This would be a risky endeavor, were it not for the fact that these exploits are typically performed during block creation. That is, the person who is determining the order of transactions within the block is in a privileged position to decide the fate of the attempted exploit; if the exploit is their own, they can guarantee its success. If there is a margin for chance, it is sufficiently small as to be negligible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aWrvIaYHI0rZJ7gPR2dBw.png" /><figcaption><strong>Figure 3: Step 2 — Allow the user’s trade through.</strong> The attacker forces the user’s trade immediately after the front running transaction. 20 ETH is exchanged for 7,053.5213 USDC by the user; previously, in the unexploited example, the user received 38,346.1538 USDC for the same trade on the same liquidity pool (therefore suffering an 81.6% decrease).</figcaption></figure><h4>Step 3: Back Run the Trade</h4><p>In the third and final step, the attacker reverses their initial front run, by swapping all the USDC they had purchased only moments ago, back for ETH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYgQohg3xBspgzAcQ9UCwA.png" /><figcaption><strong>Figure 4: Step 3 — Back run the trade.</strong> The attacker forces their own back running transaction immediately after the user’s trade has been executed. The 575,031.4616 USDC acquired in the front running step is swapped back in its entirety for 693.6444 ETH, netting the attacker 12.2767 ETH in the round trip.</figcaption></figure><p>The important thing to note here is that the attacker has risked essentially nothing, and provided nothing of value to the system, save <em>maybe</em> for their involvement in “securing the blockchain” as part of the block building process. If this latter argument is to be entertained, I doubt many would hesitate to characterize the relationship between those participating in consensus and those inhabiting the chain for its own sake as abusive.</p><h4>The Overall Result</h4><p>The steps described above detail the mechanism of the attack (figures 2–4), and for many of you there will be very little offered in the way of new information thus far. However, I am hopeful that the following perspective regarding the overall process is sufficiently novel to earn your consideration, regardless of your prior familiarity with the subject.</p><p>Imagine for a moment that we become so exhausted and complacent as a community that we simply accept that these kinds of attack vectors are insurmountable — or worse, serve the purpose of a built-in tax vehicle in addition to gas costs demanded by those governing the infrastructure. Further, imagine that it is realized that there are a lot of unnecessary steps involved in these sandwich attacks, and that it would be preferable to arrive at the same result without the superfluous ritual of performing it. I am being deliberately hyperbolic, but I promise it doesn’t matter. The point is to consider the reductionist perspective.</p><ol><li>A user decides to trade ETH for USDC on a liquidity pool with a fee rate of 0.3% and nearly $2M in liquidity.</li><li>They are expecting to send 20 ETH to the liquidity pool and receive 38,346.1538 USDC, and then commit to the transaction.</li><li>A stranger arrives and takes 12.2767 ETH without warning and for no reason.</li><li>The remaining 7.7233 ETH are sent to the liquidity pool to perform the swap.</li><li>The liquidity pool then immediately changes its fee rate to 53.63% (i.e. a 17,776.9349% increase).</li><li>The swap is performed, and the user receives 7,053.5213 USDC (in contrast to the 38,346.1538 USDC they were expecting).</li><li>Finally, the liquidity pool then immediately reverts its fee level to that prior to the user’s exchange (i.e. back to 0.3%).</li></ol><p>The steps above are completely redundant with the steps of performing a sandwich attack. The two have different mechanisms but arrive at precisely the same result; they are financially and, to some extent, computationally identical. While I would prefer everyone with an interest in the topic have a firm basis of understanding in the true mechanism, I’ll settle for a heuristic one so long as the facts regarding the precise transfer of value, and to whom, are consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7znVWFihHt_4070PmeP_3g.png" /><figcaption><strong>Figure 5: The overall result.</strong> The user sends 20 ETH, which is intercepted by the attacker, who removes 12.2767 ETH from the transaction, leaving only 7.7233 ETH for the trade. Then, the liquidity pool changes its fee level from 0.3% to 53.63%, before processing the exchange. The user then receives 7,053.5213 USDC according to the familiar swap algorithm (eqn 1) at the new fee level.</figcaption></figure><h3>Precise Sandwich Elucidation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*54RPeH-83taFFRHQzfbtPw.jpeg" /></figure><p>The sandwich attack detailed above is optimal for the state as it is presented, save for the lack of decimal places. That is, the 681.3677 ETH (in fact, 681.367696126344533020 ETH) used in the front running transaction is not an approximation, and the 12.2767 ETH (in fact, 12.276688934466993032 ETH) extracted by the attacker is the absolute maximum achievable.</p><p>Let <em>Q</em> be the total amount of ETH extracted by the attacker before gas is considered. It is a relatively easy task to nest the three swap equations together to calculate <em>Q</em> in terms of the swap fee, <em>δ</em>, the two token reserves of the liquidity pool, <em>x</em> and <em>y</em>, the number of ETH tokens sent to the liquidity pool by the user, Δ<em>x</em>ᵤ, and the amount of ETH tokens sent to the liquidity pool by the attacker during the front run, Δ<em>x</em>ₐ (eqn 2). However, the result is a little ugly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wz5nGErAeIigB6T93-N9Kw.png" /></figure><p>Reducing eqn 2 and cancelling the <em>y</em> terms yields eqn 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcr7_yCKfMShAKqp5SmCIA.png" /></figure><p>The plot of <em>Q</em> versus Δ<em>x</em>ₐ reveals the attack profits profile with respect to the number of tokens committed during the front running step. At first, visual inspection of the graph is seemingly unrevealing; however, depicting the Δ<em>x</em>ₐ dimension on a logarithmic scale helps to exaggerate the feature of interest (figure 6). An interactive plot is provided for the reader’s convenience via <a href="https://www.desmos.com/calculator/nnrgbxaytd">desmos</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBvIzmIGgq28U8hq3rOiEw.png" /><figcaption><strong>Figure 6: Q versus Δ<em>x</em>ₐ.</strong> Both plots are obtained from eqn 3; a) depicted on linear scales and b) the Δ<em>x</em>ₐ dimension on a logarithmic scale. The peak depicted in b) denotes the optimal Δ<em>x</em>ₐ token quantity to trade during the front running component of the attack.</figcaption></figure><p>The local maxima around the peak featured in figure 5 b) can be calculated from the partial derivative of eqn 3 with respect to Δ<em>x</em>ₐ, evaluated at 0 (eqn 4). The coefficients <em>A</em>, <em>B</em>, <em>C</em>, <em>D,</em> are substituting for the other terms (<em>x</em>, <em>δ</em>, and Δ<em>x</em>ᵤ), which are treated as constant for the purpose of computing the front running transaction (eqns 5–8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4QUY6LR0t5L_V8Mjth41Q.png" /></figure><p>Note that each of the coefficients <em>A</em>-<em>D</em> have the same denominator, 1-(1-<em>δ</em>)², which is an artefact of dividing through by the leading coefficient to force reduction to the monic equation type (i.e. leading coefficient = 1). Fortunately, eqn 4 is quartic, so solving for Δ<em>x</em>ₐ is not impossible, albeit inconvenient. For all realistic values (e.g. swap fee, token balances, swap amounts are greater than zero) eqn 4 has two real, and two complex roots. Only the root at Δ<em>x</em>ₐ &gt; 0 (i.e. the part needed to perform the exploit), if one exists, is presented here. Note that depending on the fee level, <em>δ</em>, liquidity depth, <em>x</em>, and the user’s trade amount, Δ<em>x</em>ᵤ, some sandwich attacks are simply not profitable for any front running trade quantity, Δ<em>x</em>ₐ.</p><p>As is characteristic of quartics, the solution is best broken into smaller pieces for readability and clarity of presentation. The solution is thus broken up into ten constituent parts, represented by the Greek letters gamma (<em>γ</em>), nu (<em>ν</em>), omega (<em>ω</em>), phi (<em>φ</em>), tau (<em>τ</em>), mu (<em>µ</em>), eta (<em>η</em>), rho (<em>ρ</em>), beta (<em>β</em>) and alpha (<em>α</em>) (eqns 9–18). These labels have no standard meaning — they are a vestige of the method I used to solve and simplify the quartic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G73RWaCK-XY4UWH1kNyVFg.png" /></figure><p>The optimum front running transaction, which determines the total returns of the sandwich attack, <em>Q</em>, can be calculated by composing eqn 19 with the quartic intermediates <em>γ</em>, <em>ν</em>, <em>ω</em>, <em>φ</em>, <em>τ</em>, <em>µ</em>, <em>η</em>, <em>ρ</em>, <em>β</em> and <em>α</em> (eqns 9–18), and the coefficients <em>A</em>, <em>B</em>, <em>C</em>, and <em>D</em> (eqns 5–8):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I8Ygdj_pf94abcDLlk1-Q.png" /></figure><p>The method described here is generic. For example, implementing the formulae above for Δ<em>x</em>ᵤ = 12.345678910, <em>x</em> = 123.45678910, and <em>δ</em> = 0.012345678910 yields an optimal front running trade of Δ<em>x</em>ₐ = 121.983219009865770262 and net profits of <em>Q</em> = 6.075819297992183389 tokens. In general, the larger the user’s intended trade compared to the depth of the liquidity pool, and the lower the swap fee, the more profitable the exploit. At <em>δ</em> = 0 the exploit becomes asymptotic at <em>Q</em> = Δ<em>x</em>ᵤ as Δ<em>x</em>ₐ → ∞, as expected. Correcting for gas consumption is trivial, as the modelled gas cost can simply be subtracted from <em>Q</em> to complete the analysis from the attacker’s perspective.</p><p>Calculating the user’s tokens obtained from the pool following the attack, Δ<em>y</em>ᵤ, is relatively straight forward (eqn 20).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIvSC1HzcBGZ9t8LqzJ9pQ.png" /></figure><p>The “effective” fee level, <em>δ*</em>, which is the apparent fee charged on the swap amount after accounting for the attacker’s rake, Δ<em>x</em>ᵤ-<em>Q</em>, is similarly trivial to calculate (eqn 21).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHnr42OrMGLsebjJbSF6cA.png" /></figure><p>I’ll save you the hassle of transcribing these equations if you promise not to use them for evil. The OptimumSandwich class (below) computes the optimum front running trade, Δ<em>x</em>ₐ, and prints an analysis sufficient to recreate figures 1–5. I consider the lack of documentation, tests, and error handling in the code block below to be appropriately compensated by the context and commentary provided by this article. Come at me (jk).</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpDNjUKG-HjfVvZDlqbfmA.jpeg" /></figure><p>The purpose of this article is to provide an authoritative overview of sandwich attacks, and to service a somewhat selfish need to have a convenient flag in the literature to which I can refer in future discussions. However, this is only the most fundamental case; there are more complex methods that are outside of the scope of this article. For example, sophisticated exploits where the attacker controls the majority of the lp token supply belonging to the liquidity pool wherein the attack is performed, deliberate “baiting” by creating an attractive price compared to competing liquidity pools, and simultaneous sandwich &amp; market arbitrage tactics are commonplace, but not explicitly discussed here. Regardless, the material provided is complete with respect to the scope of the discussion, and ought to satisfy the needs of almost any informed conversation on the topic.</p><p>I want to end this article with a challenge to the reader — both in the spirit of finding a silver lining, while also appealing to my own pedagogical ambitions. Given the mathematical descriptions presented here, it is possible to derive an expression for an “un-sandwichable” trade. That is, given the state of the pool (<em>x</em>, <em>δ</em>), there is a maximum quantity of tokens being swapped by the user, Δ<em>x</em>ᵤ, for which any attempted sandwich attack will net zero in profit for the exploiter (i.e. <em>Q</em> = 0 and by inference, Δ<em>x</em>ₐ = 0). It stands to reason that such a trade amount can and should be exposed to users via the front-end for DeFi applications running a typical constant product CFMM at the smart contract level. If you have made it this far — the challenge I issue to you is this:</p><ol><li>For a generic liquidity pool with a reserve balance of <em>x</em> ETH and a swap fee of <em>δ</em>, what quantity of ETH, Δ<em>x</em>ᵤ, can the user swap without exposing a sandwich attack opportunity?</li><li>For a generic liquidity pool with a reserve balance of <em>x</em> ETH, where the user is determined to trade a certain quantity of ETH, Δ<em>x</em>ᵤ, what swap fee setting, <em>δ</em>, would nullify the sandwich attack opportunity?</li></ol><h4>Postscript</h4><p>This article is adjacent a recent contribution from <a href="https://medium.com/@odtorson?source=post_page-----2ec7800dde68--------------------------------">Stefan Loesch</a> regarding the resistance of <a href="http://www.carbondefi.xyz/"><em>Carbon</em></a>, a trading protocol from Bancor, to sandwich attacks. Loesch’s <a href="https://medium.com/carbondefi/carbon-the-mev-sandwich-is-toast-2ec7800dde68">article</a> discusses the viability of sandwich attacks in the context of implied fee levels in the concentrated liquidity paradigm and speaks directly to the concepts embedded in the challenge questions above.</p><h3>Code Block: OptimumSandwich Class (python)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaYqtRPxdOycYOrzwUMwDA.jpeg" /></figure><pre>from decimal import Decimal, getcontext<br>getcontext().prec = 100<br><br>class OptimumSandwich:<br>    &quot;&quot;&quot;<br>    Examples: <br>    &gt;&gt;&gt; OptimumSandwich()<br>    1. The user observes a pool with 500.000000 &#39;x&#39; tokens and 1000000.000000 &#39;y&#39; tokens, and a swap fee of 0.003000.<br>    2. The user elects to swap 20.000000 &#39;x&#39; tokens and expects to receive 38346.153846 &#39;y&#39; tokens.<br>    3. First, the attacker front runs the user&#39;s trade by swapping 681.367696 &#39;x&#39; tokens for 575031.461640 &#39;y&#39; tokens.<br>    4. Then, the user&#39;s trade is allowed through; the user swaps 20.000000 &#39;x&#39; tokens for 7053.521318 &#39;y&#39; tokens.<br>    5. Finally, the attacker back runs both of the previous trades by swapping 575031.461640 &#39;y&#39; tokens for 693.644385 &#39;x&#39; tokens.<br>    6. Therefore, the attacker has extracted a total of 12.276689 &#39;x&#39; tokens from the user&#39;s transaction.<br>    7. The overall process is equivalent to the user giving away 12.276689 &#39;x&#39; tokens to the attacker, then swapping the remaining 7.723311 &#39;x&#39; tokens with the pool.<br>    8. In addition to the sacrificed &#39;x&#39; token quantity, the pool fee also appears to be increased from 0.003000 to 0.536308 (i.e. 17876.934872% increase).<br>    9. At the end of the process, the liquidity pool contains 507.723311 &#39;x&#39; tokens, and 992946.478682 &#39;y&#39; tokens.<br>    10. The user&#39;s losses are -81.605662% with respect to the expected outcome.<br>    <br>    &gt;&gt;&gt; OptimumSandwich(<br>        x = Decimal(&#39;123.45678910&#39;),<br>        y = Decimal(&#39;123456.78910&#39;),<br>        d = Decimal(&#39;0.012345678910&#39;),<br>        Dx_u = Decimal(&#39;12.345678910&#39;)<br>        )<br>    1. The user observes a pool with 123.456789 &#39;x&#39; tokens and 123456.789100 &#39;y&#39; tokens, and a swap fee of 0.012346.<br>    2. The user elects to swap 12.345679 &#39;x&#39; tokens and expects to receive 11084.784657 &#39;y&#39; tokens.<br>    3. First, the attacker front runs the user&#39;s trade by swapping 121.983219 &#39;x&#39; tokens for 60600.286699 &#39;y&#39; tokens.<br>    4. Then, the user&#39;s trade is allowed through; the user swaps 12.345679 &#39;x&#39; tokens for 2973.112594 &#39;y&#39; tokens.<br>    5. Finally, the attacker back runs both of the previous trades by swapping 60600.286699 &#39;y&#39; tokens for 128.059038 &#39;x&#39; tokens.<br>    6. Therefore, the attacker has extracted a total of 6.075819 &#39;x&#39; tokens from the user&#39;s transaction.<br>    7. The overall process is equivalent to the user giving away 6.075819 &#39;x&#39; tokens to the attacker, then swapping the remaining 6.269860 &#39;x&#39; tokens with the pool.<br>    8. In addition to the sacrificed &#39;x&#39; token quantity, the pool fee also appears to be increased from 0.012346 to 0.501727 (i.e. 4063.984954% increase).<br>    9. At the end of the process, the liquidity pool contains 129.726649 &#39;x&#39; tokens, and 120483.676506 &#39;y&#39; tokens.<br>    10. The user&#39;s losses are -73.178436% with respect to the expected outcome.<br>    &quot;&quot;&quot;<br>    def __init__(<br>        self,<br>        x: Decimal = Decimal(&#39;500&#39;), # the &#39;x&#39; token balance of the constant product liquidity pool.<br>        y: Decimal = Decimal(&#39;1_000_000&#39;), # the &#39;y&#39; token balance of the constant product liquidity pool.<br>        d: Decimal = Decimal(&#39;0.003&#39;), # the fee level (decimal, 0.003 = 0.3% = 30 bps) of the constant product liquidity pool.<br>        Dx_u: Decimal = Decimal(&#39;20&#39;) # the number of &#39;x&#39; tokens elected by the user to swap with the pool for &#39;y&#39; tokens.<br>        ):<br>        self.x = x<br>        self.y = y<br>        self.d = d<br>        self.Dx_u = Dx_u<br>        self.A = self.calculate_coefficient_A()<br>        self.B = self.calculate_coefficient_B()<br>        self.C = self.calculate_coefficient_C()<br>        self.D = self.calculate_coefficient_D()<br>        self.gamma = self.calculate_gamma()<br>        self.nu = self.calculate_nu()<br>        self.omega = self.calculate_omega()<br>        self.phi = self.calculate_phi()<br>        self.tau = self.calculate_tau()<br>        self.mu = self.calculate_mu()<br>        self.eta = self.calculate_eta()<br>        self.rho = self.calculate_rho()<br>        self.beta = self.calculate_beta()<br>        self.alpha = self.calculate_alpha()<br>        self.Dx_a = self.calculate_Dx_a()<br>        self.Dy_a = self.calculate_Dy_expected(self.Dx_a)<br>        self.Q = self.calculate_Q()<br>        self.Dy_u_expected = self.calculate_Dy_expected(self.Dx_u)<br>        self.Dy_u_obtained = self.calculate_Dy_u_obtained()<br>        self.d_u = self.calculate_d_u()<br>        self.print_analysis()<br>        <br>    def calculate_coefficient_A(self):<br>        return(<br>            + Decimal(&#39;2&#39;)*self.d*(<br>                + Decimal(&#39;2&#39;) <br>                - self.d<br>            )*(<br>                + self.Dx_u*(<br>                    + self.d <br>                    + (<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )**Decimal(&#39;2&#39;)<br>                ) <br>                + Decimal(&#39;2&#39;)*self.x<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_coefficient_B(self):<br>        return(<br>            + (<br>                + self.d*(<br>                    + self.Dx_u*(<br>                        + self.Dx_u <br>                        + Decimal(&#39;6&#39;)*self.x<br>                        - (<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )*(<br>                            + self.Dx_u <br>                            - (<br>                                + Decimal(&#39;1&#39;) <br>                                - self.d<br>                            )**Decimal(&#39;2&#39;)*(<br>                                + Decimal(&#39;2&#39;)*self.x<br>                                + self.Dx_u <br>                            )<br>                            + (<br>                                + Decimal(&#39;1&#39;) <br>                                - self.d<br>                            )*(<br>                                + Decimal(&#39;3&#39;)*self.x <br>                                - self.Dx_u<br>                            ) <br>                        )<br>                    ) <br>                    + Decimal(&#39;6&#39;)*self.x**Decimal(&#39;2&#39;)*(<br>                        + Decimal(&#39;2&#39;) <br>                        - self.d<br>                    )<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>    <br>    def calculate_coefficient_C(self):<br>        return(<br>            + (<br>                + Decimal(&#39;2&#39;)*self.x*(<br>                    + self.x<br>                    + self.d*self.Dx_u <br>                )*(<br>                    + self.Dx_u*(<br>                        + (<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )**Decimal(&#39;2&#39;) <br>                        - self.d<br>                    ) <br>                    - Decimal(&#39;2&#39;)*self.d*self.x*(<br>                        + Decimal(&#39;2&#39;) <br>                        - self.d<br>                    )<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br><br>    def calculate_coefficient_D(self):<br>        return(<br>            + self.x*(<br>                + self.x <br>                + self.d*self.Dx_u<br>            )*(<br>                + (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)*(<br>                    + self.x <br>                    + self.Dx_u<br>                )**Decimal(&#39;2&#39;) <br>                - self.x*(<br>                    + self.x <br>                    + self.d*self.Dx_u<br>                )<br>            )/(<br>                + Decimal(&#39;1&#39;) <br>                - (<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )**Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_gamma(self):<br>        return(<br>            + (<br>                + self.B<br>                - (<br>                    + (<br>                        + Decimal(&#39;3&#39;)*self.A**Decimal(&#39;2&#39;)/Decimal(&#39;8&#39;)<br>                    )<br>                )<br>            )/Decimal(&#39;6&#39;)<br>        )<br>        <br>    def calculate_nu(self):<br>        return(<br>            + (<br>                + self.A*self.C/Decimal(&#39;4&#39;)<br>            )<br>        )<br>        <br>    def calculate_omega(self):  <br>        return(<br>            + self.gamma*(<br>                + self.nu<br>                + self.B*(<br>                    self.A/Decimal(&#39;4&#39;)<br>                )**Decimal(&#39;2&#39;)<br>                - Decimal(&#39;3&#39;)*(<br>                    + self.A/Decimal(&#39;4&#39;)<br>                )**Decimal(&#39;4&#39;)<br>                - self.D<br>            )<br>        )<br>        <br>    def calculate_phi(self):<br>        return(<br>            + (<br>                + (<br>                    + (<br>                        + self.A/Decimal(&#39;2&#39;)<br>                    )**Decimal(&#39;3&#39;) <br>                    - (<br>                        + self.A*self.B<br>                    )/Decimal(&#39;2&#39;) <br>                    - self.C<br>                )/Decimal(&#39;4&#39;)<br>            )**Decimal(&#39;2&#39;)<br>        )<br>        <br>    def calculate_tau(self):<br>        return(<br>            + self.D <br>            - self.A*self.C/Decimal(&#39;4&#39;) <br>            - self.B**Decimal(&#39;2&#39;)/Decimal(&#39;12&#39;)<br>        )<br>    <br>    def calculate_mu(self):<br>        return(<br>            + (<br>                + (<br>                    + (<br>                        + self.tau<br>                    )/Decimal(&#39;3&#39;) <br>                )**Decimal(&#39;3&#39;)<br>                + (<br>                    + (<br>                        + self.omega <br>                        - self.phi<br>                        - self.gamma**Decimal(&#39;3&#39;)<br>                    )**Decimal(&#39;2&#39;)<br>                )<br>            )**(<br>            + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br><br>    def calculate_eta(self):<br>        return(<br>            + (<br>                + self.mu <br>                + self.gamma**Decimal(&#39;3&#39;)<br>                + self.phi<br>                - self.omega<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;3&#39;)<br>            )<br>        )<br>        <br>    def calculate_rho(self):<br>        return(<br>            + Decimal(&#39;2&#39;)*self.tau/(<br>                + Decimal(&#39;3&#39;)*self.eta<br>            )<br>        )<br>        <br>    def calculate_beta(self):<br>        return(<br>            + (<br>                + (<br>                    + self.A/Decimal(&#39;2&#39;)<br>                )**Decimal(&#39;2&#39;) <br>                - (<br>                    + Decimal(&#39;2&#39;)*self.B<br>                )/Decimal(&#39;3&#39;) <br>                - self.rho <br>                + Decimal(&#39;2&#39;)*self.eta<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_alpha(self):<br>        return(<br>            + (<br>                + self.A**Decimal(&#39;2&#39;)/Decimal(&#39;2&#39;) <br>                - (<br>                    + Decimal(&#39;4&#39;)*self.B<br>                )/Decimal(&#39;3&#39;) <br>                - (<br>                    + self.A**Decimal(&#39;3&#39;)/Decimal(&#39;4&#39;) <br>                    - self.A*self.B <br>                    - Decimal(&#39;2&#39;)*self.C<br>                )/self.beta <br>                - Decimal(&#39;2&#39;)*self.eta <br>                + self.rho<br>            )**(<br>                + Decimal(&#39;1&#39;)/Decimal(&#39;2&#39;)<br>            )<br>        )<br>        <br>    def calculate_Dx_a(self):<br>        return(<br>            + (<br>                + self.alpha <br>                + self.beta<br>            )/Decimal(&#39;2&#39;) <br>            - self.A/Decimal(&#39;4&#39;)<br>        )<br>        <br>    def calculate_Q(self):<br>        return(<br>            + (<br>                + self.Dx_a*(<br>                    + self.Dx_u*(<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )*(<br>                        + self.Dx_a <br>                        + self.x <br>                        - self.Dx_a*(<br>                            + Decimal(&#39;1&#39;) <br>                            - self.d<br>                        )<br>                    ) <br>                    - (<br>                        + self.Dx_a <br>                        + self.x<br>                    )*(<br>                        + self.Dx_a <br>                        + self.Dx_u <br>                        + self.x<br>                    ) <br>                    + (<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    )**Decimal(&#39;2&#39;)*(<br>                        + self.Dx_a <br>                        + self.Dx_u <br>                        + self.x<br>                    )**Decimal(&#39;2&#39;)<br>                )<br>            )/(<br>                + self.Dx_u*(<br>                    + Decimal(&#39;1&#39;) <br>                    - self.d<br>                )*(<br>                    + self.Dx_a*(<br>                        + Decimal(&#39;1&#39;) <br>                        - self.d<br>                    ) <br>                    - self.Dx_a <br>                    - self.x<br>                ) <br>                + (<br>                    + self.Dx_a <br>                    + self.x<br>                )*(<br>                    + self.Dx_a <br>                    + self.Dx_u <br>                    + self.x<br>                )<br>            )<br>        )<br>        <br>    def calculate_Dy_expected(self, Dx):<br>        return(<br>            + Dx*self.y*(<br>                + Decimal(&#39;1&#39;)<br>                - self.d<br>                )/(<br>                + self.x<br>                + Dx<br>            )<br>        )<br>    <br>    def calculate_Dy_u_obtained(self):<br>        return(<br>            + self.Dx_u*self.y*(<br>                + Decimal(&#39;1&#39;) <br>                - self.d<br>            )*(<br>                + self.Dx_a*self.d <br>                + self.x<br>            )/(<br>                + (<br>                    + self.Dx_a <br>                    + self.x<br>                )*(<br>                    + self.Dx_a <br>                    + self.Dx_u <br>                    + self.x<br>                )<br>            )<br>        )<br>        <br>    def calculate_d_u(self):<br>        return(<br>            + Decimal(&#39;1&#39;)<br>            - self.Dy_u_obtained/self.y <br>            - self.Dy_u_obtained*self.x/(<br>                + (<br>                    + self.Dx_u<br>                    - self.Q<br>                )*self.y<br>            )<br>        )<br>        <br>    def print_analysis(self):<br>        print(f&quot;1. The user observes a pool with {self.x:.6f} &#39;x&#39; tokens and {self.y:.6f} &#39;y&#39; tokens, and a swap fee of {self.d:.6f}.&quot;)<br>        print(f&quot;2. The user elects to swap {self.Dx_u:.6f} &#39;x&#39; tokens and expects to receive {self.Dy_u_expected:.6f} &#39;y&#39; tokens.&quot;)<br>        if self.Dx_a &gt; Decimal(&#39;0&#39;):<br>            print(f&quot;3. First, the attacker front runs the user&#39;s trade by swapping {self.Dx_a:.6f} &#39;x&#39; tokens for {self.Dy_a:.6f} &#39;y&#39; tokens.&quot;)<br>            print(f&quot;4. Then, the user&#39;s trade is allowed through; the user swaps {self.Dx_u:.6f} &#39;x&#39; tokens for {self.Dy_u_obtained:.6f} &#39;y&#39; tokens.&quot;)<br>            print(f&quot;5. Finally, the attacker back runs both of the previous trades by swapping {self.Dy_a:.6f} &#39;y&#39; tokens for {(self.Dx_a + self.Q):.6f} &#39;x&#39; tokens.&quot;)<br>            print(f&quot;6. Therefore, the attacker has extracted a total of {self.Q:.6f} &#39;x&#39; tokens from the user&#39;s transaction.&quot;)<br>            print(f&quot;7. The overall process is equivalent to the user giving away {self.Q:.6f} &#39;x&#39; tokens to the attacker, then swapping the remaining {(self.Dx_u - self.Q):.6f} &#39;x&#39; tokens with the pool.&quot;)<br>            print(f&quot;8. In addition to the sacrificed &#39;x&#39; token quantity, the pool fee also appears to be increased from {self.d:.6f} to {self.d_u:.6f} (i.e. {100*(self.d_u/self.d - 1):.6f}% increase).&quot;)<br>            print(f&quot;9. At the end of the process, the liquidity pool contains {(self.x + self.Dx_u - self.Q):.6f} &#39;x&#39; tokens, and {(self.y - self.Dy_u_obtained):.6f} &#39;y&#39; tokens.&quot;)<br>            print(f&quot;10. The user&#39;s losses are -{(Decimal(&#39;1&#39;) - self.Dy_u_obtained/self.Dy_u_expected)*100:.6f}% with respect to the expected outcome.&quot;)<br>        else:<br>            print(&#39;3. Any attempted sandwich attack on this trade will not benefit the exploiter in any way.&#39;)<br>        return None</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9131a2562b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carbondefi/the-optimum-sandwich-how-to-exploit-blockchain-enthusiasts-with-arbitrary-precision-e9131a2562b5">The Optimum Sandwich: How to Exploit Blockchain Enthusiasts with Arbitrary Precision</a> was originally published in <a href="https://medium.com/carbondefi">CarbonDeFi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>