<?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 Justin Gee on Medium]]></title>
        <description><![CDATA[Stories by Justin Gee on Medium]]></description>
        <link>https://medium.com/@usgeeus?source=rss-9e5e41e966c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RvC-oejy960ctty9YsX2Pg.png</url>
            <title>Stories by Justin Gee on Medium</title>
            <link>https://medium.com/@usgeeus?source=rss-9e5e41e966c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 18:25:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usgeeus/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[크롬 개발자 도구로 복사 방지된 웹페이지 텍스트 추출하기]]></title>
            <link>https://medium.com/@usgeeus/%ED%81%AC%EB%A1%AC-%EA%B0%9C%EB%B0%9C%EC%9E%90-%EB%8F%84%EA%B5%AC%EB%A1%9C-%EB%B3%B5%EC%82%AC-%EB%B0%A9%EC%A7%80%EB%90%9C-%EC%9B%B9%ED%8E%98%EC%9D%B4%EC%A7%80-%ED%85%8D%EC%8A%A4%ED%8A%B8-%EC%B6%94%EC%B6%9C%ED%95%98%EA%B8%B0-a9ea867be1b2?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ea867be1b2</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[chrome-devtools]]></category>
            <category><![CDATA[productivity-tips]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 13:18:51 GMT</pubDate>
            <atom:updated>2025-07-29T13:18:51.432Z</atom:updated>
            <content:encoded><![CDATA[<p>웹페이지에서 텍스트를 복사하려고 했는데 드래그와 복사가 모두 막혀본 경험 있으신가요?</p><p>많은 사이트가 JavaScript 이벤트와 CSS를 사용해 이를 차단하지만, 크롬 개발자 도구를 알면 쉽게 우회할 수 있습니다.</p><p>여기서는 제가 실제로 자막 텍스트를 추출한 방법을 공유합니다.</p><p>1단계 — 요소 확인</p><p>1. 원하는 텍스트에서 우클릭 → 검사 (또는 F12)</p><p>2. Elements 패널에서 실제 텍스트가 들어 있는 태그 확인</p><p>예:</p><pre>&lt;div class=”wyBDIb”&gt;Uh hello uh thanks for attending this seminar…&lt;/div&gt;</pre><p>3. 이미지가 아닌 순수 텍스트인지 확인</p><p>2단계 — 복사 차단 해제</p><p>대부분의 사이트는 다음 방식으로 차단:</p><p>- oncopy, onselectstart 등 이벤트 리스너</p><p>- user-select: none CSS</p><p>Console에 아래 코드 실행:</p><pre>document.querySelectorAll(‘*’).forEach(el =&gt; {<br>el.oncopy = el.oncut = el.onpaste = el.onselectstart = el.onmousedown = el.onmouseup = el.oncontextmenu = null;<br>});<br>const css = &#39;* { user-select: text !important; }&#39;;<br>const style = document.createElement(&#39;style&#39;);<br>style.innerHTML = css;<br>document.head.appendChild(style);</pre><p>모든 텍스트가 선택 가능해집니다.</p><p>3단계 — 전체 텍스트 추출</p><p>전체를 한 번에 가져오려면:</p><pre>(() =&gt; {<br>const elements = document.querySelectorAll(&#39;.wyBDIb&#39;);<br>const lines = Array.from(elements).map(el =&gt; el.innerText.trim());<br>const fullText = lines.join(&#39;\n&#39;);<br>console.log(fullText);<br>navigator.clipboard.writeText(fullText)<br>.then(() =&gt; console.log(&quot;✅ 전체 텍스트가 복사되었습니다.&quot;))<br>.catch(err =&gt; console.error(&quot;❌ 복사 실패:&quot;, err));<br>})();</pre><p>이렇게 하면:</p><p>- .wyBDIb 요소를 모두 찾고</p><p>- 순서대로 텍스트 추출</p><p>- 줄바꿈으로 합쳐서</p><p>- 클립보드에 자동 복사</p><p>마무리</p><p>크롬 개발자 도구와 간단한 자바스크립트만으로 복사 방지된 텍스트를 쉽게 추출할 수 있습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ea867be1b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Extract and Copy Blocked Text from Any Web Page Using Chrome DevTools]]></title>
            <link>https://medium.com/@usgeeus/how-to-extract-and-copy-blocked-text-from-any-web-page-using-chrome-devtools-2756eee49065?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2756eee49065</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[productivity-tips]]></category>
            <category><![CDATA[chrome-devtools]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 13:14:40 GMT</pubDate>
            <atom:updated>2025-07-29T13:14:40.087Z</atom:updated>
            <content:encoded><![CDATA[<h3>Have you ever tried to copy text from a webpage, only to find that it’s blocked? Websites often use JavaScript event listeners and CSS rules to disable text selection or copying. Fortunately, with a bit of knowledge of Chrome DevTools, you can easily bypass these restrictions.</h3><p>In this article, I’ll show you how I extracted transcript text from a webpage where copying was disabled — without using any browser extensions.</p><p>Step 1 — Inspect the Element</p><p>1. Right-click the desired text and choose Inspect (or press F12).</p><p>2. In the Elements panel, find the HTML tag that contains the actual text.</p><p>Example:</p><pre>&lt;div class=”wyBDIb”&gt;Uh hello uh thanks for attending this seminar…&lt;/div&gt;</pre><p>3. Confirm that the text is there in plain form (not an image).</p><p>Step 2 — Remove Copy-Blocking Restrictions</p><p>Many sites block copy via:</p><p>- oncopy, onselectstart event listeners</p><p>- user-select: none CSS styles</p><p>Open Chrome DevTools Console and paste:</p><pre>document.querySelectorAll(&#39;*&#39;).forEach(el =&gt; {<br>el.oncopy = el.oncut = el.onpaste = el.onselectstart = el.onmousedown = el.onmouseup = el.oncontextmenu = null;<br>});<br>const css = &#39;* { user-select: text !important; }&#39;;<br>const style = document.createElement(&#39;style&#39;);<br>style.innerHTML = css;<br>document.head.appendChild(style);</pre><p>Now all text becomes selectable and copyable.</p><p>Step 3 — Extract All Target Text Automatically</p><p>If you want to extract everything at once:</p><pre>(() =&gt; {<br>const elements = document.querySelectorAll(&#39;.wyBDIb&#39;);<br>const lines = Array.from(elements).map(el =&gt; el.innerText.trim());<br>const fullText = lines.join(&#39;\n&#39;);<br>console.log(fullText);<br>navigator.clipboard.writeText(fullText)<br>.then(() =&gt; console.log(&quot;✅ Copied to clipboard&quot;))<br>.catch(err =&gt; console.error(&quot;❌ Copy failed:&quot;, err));<br>})();</pre><p>This:</p><p>- Finds all .wyBDIb elements</p><p>- Extracts their text in order</p><p>- Joins them with line breaks</p><p>- Copies the result to your clipboard</p><p>Conclusion</p><p>You don’t need special extensions to copy blocked text. With Chrome DevTools and a few lines of JavaScript, you can unlock almost any text on the web. This technique works great for transcripts, articles, and other plain-text content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2756eee49065" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing a Stuck Git Submodule in Foundry Projects]]></title>
            <link>https://medium.com/@usgeeus/fixing-a-stuck-git-submodule-in-foundry-projects-c71bb83d2d5d?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c71bb83d2d5d</guid>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 07:48:31 GMT</pubDate>
            <atom:updated>2025-02-19T07:48:31.023Z</atom:updated>
            <content:encoded><![CDATA[<p>When installing a library in your Foundry project, you may occasionally run into a Git submodule issue that prevents you from either installing or removing that library. You might see errors like:</p><pre>fatal: &#39;lib/some-library&#39; already exists and is not a valid git repo</pre><p>or</p><pre>fatal: not a git repository: ... .git/modules/lib/some-library</pre><p>These errors typically occur because the library is (or was) tracked as a Git submodule, and references to that submodule still exist in your repository. Fortunately, the fix boils down to <strong>completely removing</strong> these references before reinstalling.</p><p><strong>Step-by-Step Fix</strong></p><ol><li>Remove the submodule from Git:</li></ol><pre>git submodule deinit -f -- lib/some-library<br>git rm -f lib/some-library<br>rm -rf .git/modules/lib/some-library</pre><ul><li>The first command removes the library from Git’s submodule registry.</li><li>The second command removes it from your Git index.</li><li>The third command deletes the submodule’s repo data stored under .git/modules/….</li></ul><p><strong>Edit .gitmodules (if it still has references)</strong>:</p><p>• Open your .gitmodules file.</p><ul><li>Remove the entire [submodule “lib/some-library”] section.</li></ul><p>3. <strong>Delete the library folder</strong> (if it remains):</p><pre>rm -rf lib/some-library</pre><p>4. <strong>Commit the cleanup</strong>:</p><pre>git commit -m &quot;Remove submodule references for some-library&quot;</pre><p>5. <strong>Reinstall the library</strong>:</p><pre>forge install &lt;github-username&gt;/&lt;some-library&gt; --no-commit</pre><p>Replace &lt;github-username&gt;/&lt;some-library&gt; with the actual GitHub repo you’re trying to install.</p><p>Under the hood, Foundry uses Git submodules to keep track of libraries. If you remove a submodule improperly (or do partial removal), your repository can end up in an inconsistent state. Git tries to track the submodule’s references in multiple places:</p><p>• The .gitmodules file</p><p>• The .git/modules/lib/… folder</p><p>• The main Git index</p><p>If any one of these references remains, reinstalling the library can fail because Git sees the folder as still being part of a “submodule” it can’t fully recognize.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c71bb83d2d5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[스마트 컨트랙트 Formal Verification part 2]]></title>
            <link>https://medium.com/@usgeeus/%EC%8A%A4%EB%A7%88%ED%8A%B8-%EC%BB%A8%ED%8A%B8%EB%9E%99%ED%8A%B8-formal-verification-part-2-6fcd860a0624?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fcd860a0624</guid>
            <category><![CDATA[smt-checker]]></category>
            <category><![CDATA[certora]]></category>
            <category><![CDATA[symbolic-execution]]></category>
            <category><![CDATA[formal-verification]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 09:34:50 GMT</pubDate>
            <atom:updated>2025-01-24T09:34:50.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>스마트 컨트랙트의 Formal Verification 테크닉</h3><h3>Model checking</h3><p>Model checking은 알고리즘이 스마트 컨트랙트의 formal model을 specification과 비교하여 검사하는 formal verification 기법이다. Model checking에서 스마트 컨트랙트는 종종 state-transition 시스템으로 표현되며, 허용되는 컨트랙트 state에 대한 속성은 temporal logic을 사용하여 정의된다.</p><p>Model checking을 위해서는 시스템(컨트랙트)의 추상적인 수학적 표현을 만들고 <a href="https://www.baeldung.com/cs/propositional-logic">명제 논리</a>에 뿌리를 둔 공식을 사용하여 이 시스템의 속성을 표현해야 한다. 이는 model checking 알고리즘의 작업, 즉 수학적 모델이 주어진 논리적 공식을 만족한다는 것을 증명하는 작업을 단순화한다.</p><p>Formal verification에서 model checking은 주로 시간에 따른 컨트랙트의 동작을 설명하는 temporal property를 평가하는 데 사용된다. 스마트 컨트랙트의 temporal property에는 part1에서 설명한 safety와 liveness가 포함된다.</p><p>예를 들어, 접근 제어와 관련된 보안 속성(예: 컨트랙트의 소유자만 selfdestruct를 호출할 수 있음)은 formal logic으로 작성할 수 있다. 그 후, model checking 알고리즘은 컨트랙트가 이 formal specification을 충족하는지 확인할 수 있다.</p><p>Model checking은 스마트 컨트랙트의 가능한 모든 state를 구성하고 property violation(속성 위반)을 초래하는 reachable state(도달 가능한 상태)를 찾는 state space exploration(상태 공간 탐색)을 사용한다. 그러나 이는 무한한 수의 상태(”state explosion problem”이라고도 함)로 이어질 수 있으므로 model checker는 스마트 컨트랙트의 효율적인 분석을 가능하게 하기 위해 추상화 기술에 의존한다.</p><h3>Theorem proving</h3><p>Theorem proving(정리 증명)은 스마트 컨트랙트를 포함한 프로그램의 정확성을 수학적으로 추론하는 방법이다. 이는 컨트랙트 시스템의 모델과 사양을 수학적 공식(logical statements)으로 변환하는 것을 포함한다.</p><p>Theorem proving의 목적은 이러한 statements 간의 논리적 동등성을 검증하는 것이다. “논리적 동등성(logical equivalence)”(”논리적 이중 함축(logical bi-implication)”이라고도 함)은 두 statements 사이의 관계 유형으로, 첫 번째 진술이 참인 경우에만 두 번째 진술이 참이 되는 것을 말한다.</p><p>컨트랙트 모델과 그 속성에 대한 statements 간에 필요한 관계(논리적 동등성)는 증명 가능한 진술(theorem)로 공식화된다. 자동화된 theorem prover는 formal system of inference을 사용하여 theorem의 유효성(validity)를 검증할 수 있다. 즉, theorem prover는 스마트 컨트랙트의 모델이 사양과 정확히 일치한다는 것을 결정적으로 증명할 수 있다.</p><p>Model checking이 컨트랙트를 유한 상태의 transition 시스템으로 모델링 하는 반면, theorem proving은 무한 상태 시스템의 분석을 처리할 수 있다. 그러나 이는 자동화된 theorem prover가 논리 문제가 ‘결정 가능한(decidable)’문제인지 아닌지를 항상 알 수 없다는 것을 의미한다. 따라서 theorem prover가 정확성 증명을 도출할 수 있도록 사람의 도움이 필요한 경우가 많다. 정리를 증명하는 데 사람의 노력이 필요하기 때문에 완전히 자동화된 모델 검사보다 비용이 더 많이 든다.</p><h3>Symbolic execution</h3><p>Symbolic execution은 구체적인 값(예: x==5) 대신 symbolic 값(예: x &gt; 5)을 사용해 함수를 실행하여 스마트 컨트랙트를 분석하는 방법이다. Formal verification 기법으로, symbolic execution은 컨트랙트 코드의 trace-level property를 formally reason하는데 사용된다.</p><p>Symbolic execution은 execution trace를 symbolic 입력 값에 대한 수학 공식으로 나타내며, 경로 술어(path predicate)이라고도 한다. <a href="https://en.wikipedia.org/wiki/Satisfiability_modulo_theories">SMT solver</a>는 path predicate가 “만족 가능한지(satisfiable)”(즉, 공식을 만족할 수 있는 값이 존재하는지) 확인하는데 사용된다. 취약한 경로가 만족 가능한 경우, SMT solver는 해당 경로로 실행을 유도하는 구체적인 값을 생성한다.</p><p>스마트 컨트랙트의 함수가 정수 값(x)을 입력으로 받아 x가 5보다 크거나 10보다 작을 때 revert된다고 가정해 보겠다. 일반적인 테스트는 오류를 발생시키는 x 값을 찾으려면 오류를 발생시키는 입력을 실제로 찾을 수 있다는 확신 없이 수십 개 이상의 테스트 케이스를 실행해야 한다.</p><p>반대로 symbolic execution 툴은 symbolic 값으로 함수를 실행한다: X&gt;5 ∧ X&lt;10. 그러면 관련 path predicate x = X&gt;5 ∧ X&lt;10이 SMT solver에 주어져 풀리게 된다. 특정 값이 x = X &gt; 5 ∧ X &lt; 10 공식을 만족하는 경우 SMT solver가 이를 계산한다. 예를 들어 solver는 x의 값으로 7을 산출할 수 있다.</p><p>Symbolic execution은 프로그램에 대한 입력에 의존하고 도달 가능한 모든 상태를 탐색하기 위한 입력 집합이 잠재적으로 무한하다. 그러나 예제에서 보듯이 symbolic exeuction은 property violation을 트리거하는 입력을 찾는 데 일반 테스트보다 더 효율적이다.</p><p>또한 symbolic execution은 함수에 대한 입력을 무작위로 생성하는 다른 속성 기반 기법(property-based techniques)(예: fuzzing)보다 오탐(false positive)이 더 적게 발생한다. Symbolic execution 중에 오류 상태가 트리거되면 오류를 트리거하는 구체적인 값을 생성하여 문제를 재현할 수 있다.</p><p>또한 symbolic execution은 어느 정도의 수학적 정확성 증명을 제공할 수 있다. 오버플로우 보호 기능이 있는 컨트랙트 함수의 다음 예를 보자.</p><pre>function safe_add(uint256 x, uint256 y) returns(uint256 z) {<br>	z = x + y;<br>	require(z&gt;=x);<br>	require(z&gt;=y);<br>	<br>	return z;</pre><p>Uint 오버플로우를 초래하는 execution trace는 이 공식을 만족해야 한다: z = x+y AND (z≥x) And (z≥y) AND (z&lt;x OR z&lt;y). 이러한 공식은 풀릴 가능성이 없으므로 safe_add 함수는 오버플로가 발생하지 않는다는 수학적 증거가 된다.</p><h3>스마트 컨트랙트에 Formal Verification을 사용하는 이유</h3><h3>Need for reliability</h3><p>Formal Verification은 실패시 사망, 부상 (?..) 또는 재정적 파탄과 같은 치명적인 결과를 초래할 수 있는 안전에 중요한 시스템의 정확성을 평가하는 데 사용된다. 스마트 컨트랙트는 막대한 가치를 관리하는 애플리케이션으로, 단순한 설계 오류로 인해 사용자에게 돌이킬 수 없는 손실을 초래할 수 있다. 그러나 컨트랙트 배포 전에 formal verification을 하면 블록체인에서 실행된 후 예상대로 작동할 것이라는 확신을 높일 수 있다.</p><p>특히 이더리움 가상 머신(EVM)에 배포된 코드는 일반적으로 변경 불가능하기 때문에 신뢰성은 모든 스마트 컨트랙트에서 매우 중요한 요소다. 출시 후 업그레이드에 쉽게 접근할 수 없기 때문에 컨트랙트의 신뢰성을 보장해야 하므로 formal verification이 필요하다. Formal verification은 Auditor와 테스터가 놓칠 수 있는 정수 언더플로우 및 오버플로, re-entrancy, 미비한 가스 최적화와 같은 까다로운 문제를 감지할 수 있다.</p><h3>Prove functional correctness</h3><p>프로그램 테스트는 스마트 컨트랙트가 몇 가지 요구 사항을 충족하는지 증명하는 가장 일반적인 방법이다. 여기에는 처리할 것으로 예상되는 데이터 샘플로 컨트랙트를 실행하고 그 동작을 분석하는 것이 포함된다. 컨트랙트가 샘플 데이터에 대해 예상한 결과를 반환하면 개발자는 그 정확성에 대한 객관적인 증거를 갖게 된다.</p><p>그러나 이 접근 방식은 샘플에 포함되지 않은 입력 값에 대해서는 올바른 실행을 증명할 수 없다. 따라서 컨트랙트를 테스트하면 버그를 발견하는 데 도움이 될 수 있지만(즉, 일부 코드 경로가 실행 중에 원하는 결과를 반환하지 못하는 경우), 버그가 없다는 것을 결정적으로 증명할 수는 없다.</p><p>반대로 formal verification은 스마트 컨트랙트를 실행하지 않고도 스마트 컨트랙트가 무한한 범위의 실행에 대한 요구 사항을 충족한다는 것을 공식적으로 증명할 수 있다. 이를 위해서는 올바른 컨트랙트 동작을 정확하게 설명하는 formal specification을 작성하고 컨트랙트 시스템의 formal (수학적) model을 개발해야 합니다. 그런 다음 formal verification 절차를 따라 컨트랙트 모델과 사양 간의 일관성을 확인할 수 있다.</p><p>Formal verification을 통해 컨트랙트의 비즈니스 로직이 요구 사항을 충족하는지 확인하는 문제는 증명하거나 반증할 수 있는 수학적 명제다. 명제를 공식적으로 증명함으로써 유한한 수의 단계로 무한한 수의 테스트 케이스를 검증할 수 있다. 이러한 방식으로 formal verification은 컨트랙트가 사양과 관련하여 기능적으로 올바른지 증명할 가능성이 더 높다.</p><h3>Ideal verification targets</h3><p>검증 대상은 공식적으로 검증할 시스템을 설명한다. Formal verification은 ‘임베디드 시스템’(더 큰 시스템의 일부를 구성하는 작고 단순한 소프트웨어 조각)에 가장 적합하다. 또한, 도메인별 속성을 검증하기 위한 도구를 쉽게 수정할 수 있으므로 규칙이 거의 없는 특수한 도메인에 이상적이다.</p><p>스마트 컨트랙트는 적어도 어느 정도는 이 두 가지 요건을 모두 충족한다. 예를 들어, 이더리움 컨트랙트의 크기가 작기 때문에 formal verification이 용이하다. 마찬가지로, EVM은 간단한 규칙을 따르기 때문에 EVM에서 실행되는 프로그램의 의미적 속성을 더 쉽게 지정하고 검증할 수 있다.</p><h3>더 빠른 개발 주기</h3><p>Model checking 및 symbolic execution과 같은 formal verification 기술은 일반적으로 스마트 컨트랙트 코드의 일반적인 분석(테스트 또는 audit 중에 수행)보다 더 효율적입니다. 이는 formal verification이 구체적인 값(“사용자가 5 이더를 인출하려고 하면 어떨까요?”)을 사용하는 테스트와 달리 assertion을 테스트하기 위해 symbolic 값(“사용자가 <strong>n</strong> 이더를 인출하려고 하면 어떨까요?”)에 의존하기 때문입니다.</p><p>Symbolic 입력 변수는 여러 클래스의 구체적인 값을 포괄할 수 있으므로 formal verification 접근 방식은 더 짧은 시간 내에 더 많은 코드 커버리지를 약속다. Formal verification을 효과적으로 사용하면 개발자의 개발 주기를 가속화할 수 있다.</p><p>또한, formal verification은 비용이 많이 드는 설계 오류를 줄여 탈중앙화 애플리케이션(디앱) 구축 프로세스를 개선한다. 취약점을 수정하기 위해 컨트랙트를 업그레이드하려면 (가능한 경우) 코드베이스를 광범위하게 다시 작성하고 개발에 더 많은 노력을 기울여야 한다. Formal verification은 테스터와 Auditor가 놓칠 수 있는 컨트랙트 구현의 많은 오류를 감지할 수 있으며, 컨트랙트를 배포하기 전에 이러한 문제를 수정할 수 있는 충분한 기회를 제공한다.</p><h3>Formal Verification의 단점</h3><h3>수작업 비용</h3><p>Formal Verification, 특히 사람이 증명자가 정확성 증명을 도출하도록 안내하는 반자동 검증은 상당한 수작업이 필요하다. 또한 formal specification을 작성하는 것은 높은 수준의 기술을 요구하는 복잡한 작업이다.</p><p>이러한 요소(노력과 기술)로 인해 formal verification은 테스트 및 audit과 같은 컨트랙트의 정확성을 평가하는 일반적인 방법에 비해 더 까다롭고 비용이 많이 든다. 그럼에도 불구하고 스마트 컨트랙트 구현의 오류로 인한 비용을 고려하면 전체 검증 오딧에 대한 비용을 지불하는 것이 현실적이다.</p><h3>False negatives</h3><p>Formal verification은 스마트 컨트랙트의 실행이 formal specification과 일치하는지 여부만 확인할 수 있다. 따라서 사양이 스마트 컨트랙트의 예상 동작을 제대로 설명하는지 확인하는 것이 중요하다.</p><p>사양이 제대로 작성되지 않은 경우, 취약한 실행을 가리키는 property violation은 formal verification 오딧에서 감지할 수 없다. 이 경우 개발자는 스마트 컨트랙트에 버그가 없다고 잘못 생각할 수 있다.</p><h3>성능 문제</h3><p>Formal verification은 여러 가지 성능 문제를 야기한다. 예를 들어, model checking 및 symbolic execution중에 발생하는 상태 및 경로 폭발 문제(path explosion problems)는 각각 검증 절차에 영향을 미칠 수 있다. 또한 formal verification 도구는 underlying layer에서 SMT solver 및 기타 제약 조건 solver를 사용하는 경우가 많으며, 이러한 solver는 계산 집약적인 절차에 의존한다.</p><p>또한 프로그램이 종료되지 않을 수도 있기 때문에 프로그램 검증자가 (논리 공식으로 설명되는) 속성이 충족될 수 있는지 여부(“<a href="https://en.wikipedia.org/wiki/Decision_problem">decidability problem</a>”)를 판단하는 것이 항상 가능한 것은 아니다. 따라서 컨트랙트가 잘 명시되어 있어도 일부 속성을 증명하는 것이 불가능할 수 있다.</p><h3>이더리움 스마트 컨트랙트를 위한 Formal Verification 도구</h3><h3>Specification languages for creating formal specifications</h3><p><strong>Act</strong> — Act를 사용하면 스토리지 업데이트, 사전/후제 조건 및 컨트랙트 불변성을 지정할 수 있다. 또한 도구 제품군에는 Coq, SMT solver 또는 hevm을 통해 많은 속성을 증명할 수 있는 증명 백엔드도 있다.</p><ul><li><a href="https://github.com/ethereum/act">GitHub(opens in a new tab)</a></li><li><a href="https://ethereum.github.io/act/">Documentation(opens in a new tab)</a></li></ul><p><strong>Scribble</strong> — Scribble은 Scribble specification language의 코드 주석을 사양을 체크하는 구체적인 assertion(concrete assertion)으로 변환한다. • <a href="https://docs.scribble.codes/">Documentation(opens in a new tab)</a></p><p><strong>Dafny</strong> — Dafny는 코드의 정확성을 추론하고 증명하기 위해 high level의 주석을 사용하는 verification-ready 프로그래밍 언어다. • <a href="https://github.com/dafny-lang/dafny">GitHub(opens in a new tab)</a></p><h3>정확성 확인을 위한 Program Verifier</h3><p><strong>Certora Prover</strong> — ****Certora Prover는 스마트 컨트랙트에서 코드 정확성을 확인하기 위한 자동 formal verification 도구다. Specification은 CVL(Certora 검증 언어)로 작성되며, 정적 분석과 제약 조건 해결의 조합을 사용하여 property violation을 감지한다.</p><ul><li><a href="https://www.certora.com/">Website(opens in a new tab)</a></li><li><a href="https://docs.certora.com/en/latest/index.html">Documentation(opens in a new tab)</a></li></ul><p><strong>솔리디티 SMTChecker</strong> — 솔리디티의 SMTChecker는 SMT(<em>Satisfiability Modulo Theories</em>) 및 Horn solving을 기반으로 하는 built-in 모델 검사기다. 컴파일 중에 컨트랙트의 소스 코드가 specification과 일치하는지 확인하고 safety 속성 위반 여부를 정적으로 검사한다. • <a href="https://github.com/ethereum/solidity">GitHub(opens in a new tab)</a></p><p><strong>solc-verify</strong> — 솔리디티 컴파일러의 확장 버전으로, 주석과 모듈식 프로그램 검증을 사용하여 솔리디티 코드에 대해 자동화된 formal verification을 수행할 수 있다. • <a href="https://github.com/SRI-CSL/solidity">GitHub(opens in a new tab)</a></p><p><strong>KEVM</strong> — KEVM은 K 프레임워크로 작성된 이더리움 가상 머신(EVM)의 formal semantics다. KEVM은 실행 가능하며, 도달 가능성 논리(reachability logic)를 사용해 특정 속성 관련 assertion을 증명할 수 있다.</p><ul><li><a href="https://github.com/runtimeverification/evm-semantics">GitHub(opens in a new tab)</a></li><li><a href="https://jellopaper.org/">Documentation(opens in a new tab)</a></li></ul><h3>Theorem proving을 위한 논리적 프레임워크</h3><p><strong>Isabelle</strong> — Isabelle/HOL은 수학 공식을 formal language로 표현할 수 있게 해주고 그 공식을 증명할 수 있는 도구를 제공하는 증명 도우미다. 주요 응용 분야는 수학적 증명의 공식화, 특히 컴퓨터 하드웨어 또는 소프트웨어의 정확성 증명, 컴퓨터 언어 및 프로토콜의 속성 증명 등 formal verification이다.</p><ul><li><a href="https://github.com/isabelle-prover">GitHub(opens in a new tab)</a></li><li><a href="https://isabelle.in.tum.de/documentation.html">Documentation(opens in a new tab)</a></li></ul><p><strong>Coq</strong> — Coq는 theorems를 사용하여 프로그램을 정의하고 기계가 검사한 정확성 증명을 대화형으로 생성할 수 있는 대화형 theorem prover다.</p><ul><li><a href="https://github.com/coq/coq">GitHub(opens in a new tab)</a></li><li><a href="https://coq.github.io/doc/v8.13/refman/index.html">Documentation(opens in a new tab)</a></li></ul><h3>스마트 컨트랙트의 취약한 패턴을 탐지하기 위한 Symbolic execution 기반 도구</h3><p><strong>Manticore</strong> — Symbolic execution 기반 EVM 바이트코드 분석 도구.</p><ul><li><a href="https://github.com/trailofbits/manticore">GitHub(opens in a new tab)</a></li><li><a href="https://github.com/trailofbits/manticore/wiki">Documentation(opens in a new tab)</a></li></ul><p><strong>hevm</strong> — EVM 바이트코드를 위한 symbolic execution 엔진 및 동등성 검사기입니다.</p><p>• <a href="https://github.com/dapphub/dapptools/tree/master/src/hevm">GitHub(opens in a new tab)</a></p><p><strong>Mythril</strong> — 이더리움 스마트 컨트랙트의 취약점을 탐지하기 위한 symbolic execution 도구다.</p><ul><li><a href="https://github.com/ConsenSys/mythril-classic">GitHub(opens in a new tab)</a></li><li><a href="https://mythril-classic.readthedocs.io/en/develop/">Documentation(opens in a new tab)</a></li></ul><h3>Further reading</h3><ul><li><a href="https://runtimeverification.com/blog/how-formal-verification-of-smart-contracts-works/">How Formal Verification of Smart Contracts Works(opens in a new tab)</a></li><li><a href="https://media.consensys.net/how-formal-verification-can-ensure-flawless-smart-contracts-cbda8ad99bd1">How Formal Verification Can Ensure Flawless Smart Contracts(opens in a new tab)</a></li><li><a href="https://github.com/leonardoalt/ethereum_formal_verification_overview">An Overview of Formal Verification Projects in the Ethereum Ecosystem(opens in a new tab)</a></li><li><a href="https://runtimeverification.com/blog/end-to-end-formal-verification-of-ethereum-2-0-deposit-smart-contract/">End-to-End Formal Verification of Ethereum 2.0 Deposit Smart Contract(opens in a new tab)</a></li><li><a href="https://www.zellic.io/blog/formal-verification-weth">Formally Verifying The World’s Most Popular Smart Contract(opens in a new tab)</a></li><li><a href="https://docs.soliditylang.org/en/v0.8.15/smtchecker.html">SMTChecker and Formal Verification(opens in a new tab)</a></li></ul><p>원본 : <a href="https://ethereum.org/en/developers/docs/smart-contracts/formal-verification/">https://ethereum.org/en/developers/docs/smart-contracts/formal-verification/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fcd860a0624" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[스마트 컨트랙트 Formal Verification part 1]]></title>
            <link>https://medium.com/@usgeeus/%EC%8A%A4%EB%A7%88%ED%8A%B8-%EC%BB%A8%ED%8A%B8%EB%9E%99%ED%8A%B8-formal-verification-baf808addd24?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/baf808addd24</guid>
            <category><![CDATA[formal-verification]]></category>
            <category><![CDATA[hoare-style-specification]]></category>
            <category><![CDATA[formal-specification]]></category>
            <category><![CDATA[eth]]></category>
            <category><![CDATA[trace-level-properties]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 05:45:24 GMT</pubDate>
            <atom:updated>2025-01-24T05:54:23.374Z</atom:updated>
            <content:encoded><![CDATA[<p>Formal Verification은 스마트 컨트랙트 보안을 개선하기 위해 권장되는 기술 중 하나다. <a href="https://www.brookings.edu/articles/formal-methods-as-a-path-toward-better-cybersecurity/">Formal method</a>(정형기법)을 사용하여 프로그램을 지정, 설계, 검증하는 Formal Verification은 중요한 하드웨어 및 소프트웨어 시스템의 정확성을 보장하기 위해 수년 동안 사용되어 왔다. Formal Verification은 컨트랙트의 비즈니스 로직이 미리 정의된 사양을 충족하는지 증명할 수 있다. Formal Verification는 unit test나 fuzz test보다 스마트 컨트랙트의 기능이 올바르다는 것을 더 강력하게 보장할 수 있다(모든 경우 X).</p><p>정형기법의 정의</p><ul><li>수리, 논리에 기반하여 하드웨어 시스템 또는 소프트웨어 시스템을 명세, 개발, 검증하는 방법들</li><li>정형기법은 정형 명세, 정형 검증 등으로 나뉠 수 있다.</li></ul><p><strong>[출처]</strong> <a href="https://blog.naver.com/bycho211/220923837907">Formal Methods (정형기법)</a>|<strong>작성자</strong> <a href="https://blog.naver.com/bycho211">bycho211</a></p><h3>Formal Verification 이란?</h3><p>Formal Verification은 <strong>Formal Specification</strong>에 따라 시스템의 정확성을 평가하는 프로세스를 말한다. 간단히 말해, 시스템의 동작이 몇 가지 요구 사항을 충족하는지(즉, 우리가 원하는 대로 작동하는지) 확인할 수 있다. 스마트 컨트랙트의 예상 동작은 <strong>Formal Modeling</strong>을 사용하여 기술되며, <a href="https://en.wikipedia.org/wiki/Specification_language">specification language</a>(사양 언어)는 formal properties를 생성할 수 있게 해준다. 그런 다음 Formal Verification 기술을 통해 컨트랙트의 구현이 사양을 준수하는지 검증하고, 정확성에 대한 수학적 증명을 도출할 수 있다. 컨트랙트의 사양을 만족하면, “기능적으로 정확함(functionally correct)”, “설계상 정확함(correct by design)” 또는 “구성상 정확함(correct by construction)”으로 설명될 수 있다.</p><h3>Formal Model 이란?</h3><p>컴퓨터 과학에서 Formal Model은 계산 프로세스에 대한 수학적 설명이다. 프로그램은 수학적 함수(방정식)로 추상화되며, 모델은 입력이 주어졌을 때 함수의 출력을 계산하는 방법을 설명한다. Formal Model은 프로그램의 동작을 분석할 수 있는 추상화 수준을 제공한다. Formal Model이 존재하면 해당 모델의 원하는 속성(properties)를 설명하는 Formal Specification을 만들 수 있다.</p><p>Formal Verification을 위해 스마트 컨트랙트를 모델링하는 데는 다양한 기술이 사용된다. 예를 들어 일부 모델은 스마트 컨트랙트의 high level 동작을 추론하는 데 사용된다. 이러한 모델링 기법은 스마트 컨트랙트에 블랙박스 관점(내부 로직을 보지 않고, 입력과 출력만을 보는 것)을 적용하여 입력을 받고 해당 입력을 기반으로 연산을 실행하는 시스템으로 간주한다.</p><h3>High-level Model vs Formal Model</h3><p>High level 모델은 스마트 컨트랙트와 EOA, CA, 블록체인 환경과 같은 외부 주체 간의 관계에 중점을 둔다. 이러한 모델은 특정 사용자의 interaction에 대한 응답으로 컨트랙트가 어떻게 작동해야 하는지 지정하는 속성을 정의하는 데 유용하다.</p><p>반대로 Formal Model은 스마트 컨트랙트의 낮은 수준의 동작에 초첨을 맞춘다. High level 모델은 컨트랙트의 기능을 추론하는 데 도움이 될 수 있지만, 구현의 내부 작동에 대한 세부 사항을 파악하지 못할 수 있다. Low level 모델은 프로그램 분석에 화이트박스(블랙박스와 반대) 보기를 적용한다.</p><h3>Formal Specification 이란?</h3><p>사양은 단순히 특정 시스템이 충족해야 하는 기술적 요구 사항이다. 프로그래밍에서 사양은 프로그램 실행에 대한 일반적인 아이디어(즉, 프로그램이 수행햐나는 작업)을 나타낸다.</p><p>스마트 컨트랙트의 맥락에서 Formal Specification은 컨트랙트가 충족해야 하는 요구 사항에 대한 formal description인 속성(properties)을 의미한다. 이러한 속성은 Invariants로 설명되며, 예외 없이 가능한 모든 상황에서 참으로 유지되어야 하는 컨트랙트 실행에 대한 논리적 주장을 나타낸다.</p><p>따라서 Formal Specification은 스마트 컨트랙트의 의도된 실행을 설명하는 formal language로 작성된 문장의 모음으로 생각할 수 있다. 사양은 컨트랙트의 속성을 다루고 다양한 상황에서 컨트랙트가 어떻게 작동해야 하는지 정의한다. Formal Verification의 목적은 스마트 컨트랙트가 이러한 Invariant 속성을 가지고 있는지, 실행 중에 이러한 속성이 위반되지 않는지 확인하는 것이다.</p><p>Formal Specification은 스마트 컨트랙트의 안전한 구현을 개발하는 데 매우 중요하다. 불변성을 구현하지 못하거나 실행 중에 속성이 위반되는 컨트랙트는 기능을 손상시키거나 악의적인 악용을 유발할 수 있는 취약점에 노출되기 쉽다.</p><h3>스마트 컨트랙트를 위한 Formal Specification의 유형</h3><p>Formal Specifications는 프로그램 실행의 정확성에 대한 수학적 추론을 가능하게 한다. Formal Model과 마찬가지로 Formal Specifications은 high level의 속성이나 컨트랙트 구현의 low level 동작을 나타낼 수 있다.</p><p>Formal Specification은 프로그램의 속성에 대한 Formal Reasoning을 가능하게 하는 <a href="https://en.wikipedia.org/wiki/Logic_programming">프로그램 로직</a>의 요소를 사용하여 도출된다. 프로그램 로직에는 프로그램의 예상 동작을 수학적 언어로 표현하는 공식적인 규칙이 있다. <a href="https://en.wikipedia.org/wiki/Reachability_problem">Reachabilitiy Logic</a>, <a href="https://en.wikipedia.org/wiki/Temporal_logic">Temporal Logic</a>, <a href="https://en.wikipedia.org/wiki/Hoare_logic">Hoare Logic</a> 등 다양한 프로그램 로직이 Formal Specification을 작성하는데 사용된다.</p><p>스마트 컨트랙트의 Formal Specification은 크게 high level 또는 low level로 분류할 수 있다. 어떤 범주에 속하든, 분석 대상 시스템의 속성을 적절하고 명확하게 설명해야 한다.</p><h3>High-level specifications</h3><p>이름에서 알 수 있듯이 high level specification(’model-oriented specification’이라고도 함)은 프로그램의 상위 수준 동작을 설명한다. High-level specification은 스마트 컨트랙트를 <a href="https://en.wikipedia.org/wiki/Finite-state_machine">유한 상태 머신</a>(finite-state machine, FSM)으로 모델링하며, 어떤 연산을 수행하여 상태(state) 전환할 수 있고, <strong>Temporal Logic</strong>을 사용하여 FSM 모델의 formal properties를 정의하는 데 사용된다.</p><p>Temporal Logic은 “시간 측면에서 한정된 명제(예: ‘나는 항상 배가 고프다’ 또는 ‘나는 결국 배가 고플 것이다’)에 대해 추론하는 규칙’이다. Formal Verification에 적용될 때, Temporal Logic은 state machine으로 모델링된 시스템의 올바른 동작에 대한 주장을 기술하는 데 사용된다. 구체적으로, Temporal Logic은 스마트 컨트랙트가 있을 수 있는 미래 state와 state의 변화 방법을 설명할 수 있다.</p><p>High-level specification은 일반적으로 스마트 컨트랙트의 두 가지 중요한 시간적 속성, <strong>safety</strong> 그리고 <strong>liveness</strong>,을 명시한다.</p><h3>Safety 속성</h3><p>Safety 속성은 “어떤 나쁜 일은 일어나지 않는다”는 개념을 나타내며, 일반적으로 불변성(invariance)을 표현한다. Saftety 속성은 <a href="https://www.techtarget.com/whatis/definition/deadlock">deadlock</a> 상태로부터의 탈출과 같은 일반적인 소프트웨어 요구 사항을 정의하거나, 컨트랙트에 대한 도메인별 속성(예: 함수에 대한 액세스 제어의 불변성, 상태 변수의 허용 가능한 값, 토큰 전송 조건)을 표현할 수 있다.</p><p>예를 들어 ERC-20 토큰 컨트랙트에서 transfer()또는 transferFrom()을 사용하기 위한 조건을 다루는 안전 요구사항을 살펴보겠다. “전송하는 자의 잔액은 전송할 토큰의 요청 금액보다 낮지 않아야 한다.”. 컨트랙트 불변성에 대한 이러한 자연어 설명은 공식적인(수학적) 사양으로 변환할 수 있으며, 이를 통해 유효성을 엄격하게 검사할 수 있다.</p><h3>Liveness 속성</h3><p>Liveness 속성은 “결국 좋은 일이 일어난다”고 주장하며, 컨트랙트의 서로 다른 state의 업데이트 기능과 관련이 있다. Liveness 속성의 예로 ‘유동성’을 들 수 있는데, 출금을 요청할 시에 사용자에게 잔액을 전송할 수 있는 컨트랙트의 기능을 의미한다. 이 속성이 위반되면 사용자는 <a href="https://www.cnbc.com/2017/11/08/accidental-bug-may-have-frozen-280-worth-of-ether-on-parity-wallet.html">Parity Wallet 사건</a>에서 발생한 것처럼 컨트랙트에 있는 자산을 인출할 수 없게 된다.</p><h3>Low-level specifications</h3><p>High-level specification은 컨트랙트의 유한 상태 머신을 기준으로 이 모델의 필요한 속성을 정의한다. 반면 Low-level specifications(”propoerty-oriented specifications”이라고도 불림)은 종종 프로그램(스마트 컨트랙트)을 수학적 함수 모음으로 구성된 시스템으로 모델링하고 해당 시스템의 올바른 동작을 설명한다.</p><p>Low-level specification은 프로그램 트레이스(trace)를 분석하고 이러한 트레이스를 통해 스마트 컨트랙트의 속성을 정의한다. 트레이스는 스마트 컨트랙트의 상태를 변경하는 함수 실행 시퀀스를 의미하며, low-level specification은 컨트랙트의 내부 실행에 대한 요구 사항을 지정하는 데 도움이 된다.</p><p>Low-level specification은 <strong>Hoare-style properties</strong> 또는 실행 경로의 불변성(invariants on execution paths)으로 제공될 수 있다.</p><h3>Hoare-style specification</h3><p><a href="https://en.wikipedia.org/wiki/Hoare_logic">Hoare logic</a>은 스마트 컨트랙트의 정확성을 추론하기 위한 일련의 formal rules를 제공한다. Hoare-style 속성은 Hoare 트리플 {P}c{Q}로 표현되며, 여기서 c는 프로그램이고 P와 Q는 c의 상태에 대한 술어로, 각각 전제 조건과 후제 조건으로 설명된다.</p><p>전제 조건은 함수의 올바른 실행에 필요한 조건을 설명하는 술어로, 컨트랙트에 호출하는 사용자는 이 조건을 충족해야 한다. 후제 조건은 함수가 올바르게 실행될 경우 설정되는 조건을 설명하는 술어로, 사용자는 함수를 호출한 후 이 조건이 참일 것으로 기대할 수 있다. Hoare logic의 불변성은 함수의 실행에 의해 유지되는 술어다.</p><p>Hoare-style specification은 부분적 정확성 또는 전체 정확성을 보장할 수 있다. 함수가 실행되기 전에 전제 조건이 참이면 컨트랙트 함수의 구현은 “부분적으로 올바르다”고 하며, 실행이 종료된다면 후제 조건도 참이다. 함수가 실행되기 전에 전제 조건이 참이고 실행이 종료되는 것이 보장되며, 그리고 실행이 종료되고 후제 조건이 참이면 전체 정확성을 얻는다.</p><p>일부 실행은 종료되기 전에 지연되거나 전혀 종료되지 않을 수 있기 때문에 전체 정확성 증명을 얻는 것은 어렵다. 하지만 이더리움의 가스 메커니즘은 무한한 프로그램 루프(실행이 성공적으로 종료되거나 ‘가스 부족’ 오류로 인해 종료)를 방지하므로, 실행이 종료되는지 여부는 논쟁의 여지가 있다고 한다.</p><p>Hoare logic을 사용해 만든 스마트 컨트랙트 사양에는 컨트랙트 내 함수 및 루프 실행을 위한 전제 조건, 후제 조건, 불변성이 정의된다. 전제 조건에는 종종 함수에 대한 잘못된 입력 가능성이 포함되며, 후제 조건에는 이러한 입력에 대한 예상 응답(예: 특정 예외 발생)이 설명되어 있다. 이러한 방식으로 Hoare-style property는 컨트랙트 구현의 정확성을 보장하는데 효과적이다.</p><p>많은 공식 검증 프레임워크는 함수의 의미론적 정확성(semantic correctness)을 증명하기 위해 Hoare-style specification을 사용한다. 솔리디티에서 require 및 assert 문을 사용하여 컨트랙트 코드에 직접 Hoare-style property(assertion)을 추가하는 것이 가능하다.</p><p>require 문은 전제 조건이나 불변성을 표현하며 사용자 입력을 검증하는 데 자주 사용되며, assert는 안전에 필요한 후제 조건을 검증하는데 주로 사용한다. (꼭 그렇지만은 않다, 서로 바꿔서 사용할 수 있다.) 예를 들어, 함수에 대한 적절한 접근 제어(safety 속성의 예)는 호출 계정의 신원을 확인하는 전제 조건으로 require를 사용하여 달성할 수 있다. 마찬가지로, 컨트랙트에서 허용되는 상태 변수의 불변값(예: 유통되는 총 토큰 수)은 함수 실행 후 컨트랙트의 상태를 확인하기 위해 assert를 사용하여 위반으로부터 보호할 수 있습니다.</p><h3>Trace-level properties</h3><p>Trace-level properties는 컨트랙트를 여러 상태 간에 변화하는 작업과 이러한 작업 간의 관계를 설명한다. 앞서 설명한 것처럼 trace는 특정 방식으로 컨트랙트의 상태를 변경하는 일련의 작업이다.</p><p>이 접근 방식은 스마트 컨트랙트를 미리 정의된 상태(state variables)와 미리 정의된 트랜지션 세트(contract functions)가 있는 state-transition 시스템으로 모델을 사용한다. 또한, 프로그램의 실행 흐름을 그래픽으로 표현한 <a href="https://www.geeksforgeeks.org/software-engineering-control-flow-graph-cfg/">control flow graph</a>(CFG)는 종종 컨트랙트의 operational semantic을 설명하는 데 사용된다. 여기서 각 trace는 control flow graph에서 경로로 표시된다.</p><p>주로 trace-level specification은 스마트 컨트랙트의 내부 실행 패턴을 추론하는 데 사용된다. trace-level property를 생성함으로써 스마트 컨트랙트에 허용되는 실행 경로(즉, 상태 전환)를 주장한다. Symbolic execution과 같은 기술을 사용하면 formal model에 정의되지 않은 경로를 따라 실행되지 않는다는 것을 공식적으로 검증할 수 있다.</p><p>Trace-level property를 설명하기 위해 공개적으로 접근할 수 있는 함수가 있는 DAO 컨트랙트의 예를 사용하겠다. 여기서는 DAO 컨트랙트를 통해 사용자가 다음과 같은 작업을 수행할 수 있다고 가정한다.</p><ul><li>자금 입금</li><li>자금을 입금한 후 제안에 투표하기</li><li>제안에 투표하지 않을 경우 환불 요청하기</li></ul><p>Trace-level property의 예로는 “자금을 입금하지 않은 사용자는 제안서에 투표할 수 없음” 또는 “제안서에 투표하지 않은 사용자는 항상 환불을 청구할 수 있어야 함”이 있다. 두 속성 모두 선호하는 실행 순서(자금을 입금하기 전에는 투표할 수 없고, 제안에 투효한 후에는 환불을 요청할 수 없음)을 주장한다.</p><p>원본 : <a href="https://ethereum.org/en/developers/docs/smart-contracts/formal-verification/">https://ethereum.org/en/developers/docs/smart-contracts/formal-verification/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baf808addd24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap V4 Limit Order Hook part 2]]></title>
            <link>https://medium.com/tokamak-network/uniswap-v4-limit-order-hook-part-2-c130997a4481?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c130997a4481</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[onther]]></category>
            <category><![CDATA[tokamak-network]]></category>
            <category><![CDATA[uniswap]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 07:33:34 GMT</pubDate>
            <atom:updated>2023-11-21T07:45:32.357Z</atom:updated>
            <content:encoded><![CDATA[<h4>Smart Contract Source Code Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*rU2eWbIxMAo0jAa0w_J8OQ.png" /><figcaption>Uniswap V4 Logo (Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">In the first post</a>, I covered limit orders in V3, V4 Contracts Overview, V4 hook flow, hook contract setup and CREATE2 deployment, pool creation, and placing pending orders.</p><p>In this post, I’ll cover processing and withdrawing limit orders, as well as some other things I haven’t covered yet.</p><p>*This article requires some understanding of Uniswap V3 to read.</p><ul><li>Korean version of the article can be found below:</li></ul><ul><li><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%ED%9B%85-part-1-1075a8c9e654">Uniswap V4 지정가 주문 훅 part 1</a></li><li><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%EB%B6%84%EC%84%9D-%EC%8B%9C%EB%A6%AC%EC%A6%88-part-2-6d46e01108a6">Uniswap V4 지정가 주문 훅 part 2</a></li></ul><p>The table of contents is as follows</p><ul><li>Swap &amp; After Swap</li><li>Withdraw</li><li>Hook Contract Test Setup in the Foundry Environment</li><li>Testing Limit Orders</li><li>EIP-1153: Transient Storage</li></ul><h3>Swap &amp; After Swap</h3><p>The following is a sequence diagram for the Swap &amp; AfterSwap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEsQo3swdRkN3ck22LQEQg.png" /><figcaption>Swap &amp; After Swap, Sequence Diagram</figcaption></figure><p>Now I’ll cover the swap to change the tick and the afterSwap hook to fulfill the limit order.</p><p>First, swap updates slot0 without much change from V3 other than checking the hook flag before and after the swap. Of course, it will acquire a lock, make the delta value zero, and move out of the lock.</p><p>You can see the lockAcquired function in v4-core/contracts/test/PoolSwapTest.sol.</p><pre>function lockAcquired(bytes calldata rawData) external returns (bytes memory) {<br>    require(msg.sender == address(manager));<br>    CallbackData memory data = abi.decode(rawData, (CallbackData));<br><br>    BalanceDelta delta = manager.swap(data.key, data.params, new bytes(0));<br>  if (data.params.zeroForOne) {<br>        if (delta.amount0() &gt; 0) {<br>            if (data.testSettings.settleUsingTransfer) {<br>                if (data.key.currency0.isNative()) {<br>                    manager.settle{value: uint128(delta.amount0())}(data.key.currency0);<br>                } else {<br>                    IERC20Minimal(Currency.unwrap(data.key.currency0)).transferFrom(<br>                        data.sender, address(manager), uint128(delta.amount0())<br>                    );<br>                    manager.settle(data.key.currency0);<br>                }<br>            } else {<br>                // the received hook on this transfer will burn the tokens<br>                manager.safeTransferFrom(<br>                    data.sender,<br>                    address(manager),<br>                    uint256(uint160(Currency.unwrap(data.key.currency0))),<br>                    uint128(delta.amount0()),<br>                    &quot;&quot;<br>                );<br>            }<br>        }<br>        if (delta.amount1() &lt; 0) {<br>            if (data.testSettings.withdrawTokens) {<br>                manager.take(data.key.currency1, data.sender, uint128(-delta.amount1()));<br>            } else {<br>                manager.mint(data.key.currency1, data.sender, uint128(-delta.amount1()));<br>            }<br>        }<br>    } else {<br>       ...<br>}</pre><p>The poolManager’s swap function returns delta. For tokenIn, the delta value will be positive in the poolManager contract, and transferFrom and settle will make the delta value zero, just like when providing liquidity. For tokenOut, the delta value is negative in the poolManager contract, and a function called take is used to make the delta value zero.</p><p>We covered transferFrom and settle when providing liquidity, so let’s take a look at the take function.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function take(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>    _accountDelta(currency, amount.toInt128());<br>    reservesOf[currency] -= amount;<br>    currency.transfer(to, amount);<br>}</pre><p>It’s very simple. The _accountDelta function adds an amount to the delta value to make it go from negative to zero, updates the reservesOf variable, and transfers it.</p><p>And in the swap function of the PoolManager contract, we check the afterSwap flag and execute the afterSwap function of the limitOrder contract as shown below.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function swap(<br>    PoolKey memory key,<br>    IPoolManager.SwapParams memory params,<br>    bytes calldata hookData<br>) external override noDelegateCall onlyByLocker returns<br> ...<br> if (key.hooks.shouldCallAfterSwap()) {<br>      if (key.hooks.afterSwap(msg.sender, key, params, delta, hookData) != IHooks.afterSwap.selector) {<br>          revert Hooks.InvalidHookResponse();<br>      }<br>  }</pre><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function afterSwap(<br>    address,<br>    PoolKey calldata key,<br>    IPoolManager.SwapParams calldata params,<br>    BalanceDelta,<br>    bytes calldata<br>) external override poolManagerOnly returns (bytes4) {<br>    (int24 tickLower, int24 lower, int24 upper) = _getCrossedTicks(key.toId(), key.tickSpacing);<br>    if (lower &gt; upper) return LimitOrder.afterSwap.selector;<br><br>    // note that a zeroForOne swap means that the pool is actually gaining token0, so limit<br>    // order fills are the opposite of swap fills, hence the inversion below<br>    bool zeroForOne = !params.zeroForOne;<br>    for (; lower &lt;= upper; lower += key.tickSpacing) {<br>        _fillEpoch(key, lower, zeroForOne);<br>    }<br><br>    setTickLowerLast(key.toId(), tickLower);<br>    return LimitOrder.afterSwap.selector;<br>}</pre><p>First, it uses the poolManagerOnly modifier to check if msg.sender is a poolManager.</p><p>In the afterSwap function, the user doing the swap is going through a “for” loop and filling all the limit orders that meet the conditions of the “for” loop through the _fillEpoch function. In the “for” loop, the condition variable increments by tickSpacing, from tickLowerLast to the new tick that was changed by the swap. This leads to the swap costing more gas.</p><p>*We mentioned at the beginning that pool deployer can freely set the tickSpacing and fee tier. If you make the tickSpacing somewhat larger, you can make less “for” loops, but the tick range of the limit order will be wider and the UX will be worse. Choosing a smaller value for tickSpacing does the opposite. If you set the “fee” low, the order router or UniswapX will catch this pool and process the limit order faster, and if you set it high, the users who placed the limit order will receive an accumulated extra fee, which means they end up getting filled at a better price. It’s important to consider a number of factors to determine the appropriate tickSpacing and fee.</p><p>Let’s look at the _fillEpoch function in v4-periphery/contracts/hooks/examples/LimitOrder.sol.</p><pre>function _fillEpoch(PoolKey calldata key, int24 lower, bool zeroForOne) internal {<br>    Epoch epoch = getEpoch(key, lower, zeroForOne);<br>    if (!epoch.equals(EPOCH_DEFAULT)) {<br>        EpochInfo storage epochInfo = epochInfos[epoch];<br><br>        epochInfo.filled = true;<br><br>        (uint256 amount0, uint256 amount1) = abi.decode(<br>            poolManager.lock(<br>                abi.encodeCall(this.lockAcquiredFill, (key, lower, -int256(uint256(epochInfo.liquidityTotal))))<br>            ),<br>            (uint256, uint256)<br>        );<br>        unchecked {<br>            epochInfo.token0Total += amount0;<br>            epochInfo.token1Total += amount1;<br>        }<br>        setEpoch(key, lower, zeroForOne, EPOCH_DEFAULT);<br>        emit Fill(epoch, key, lower, zeroForOne);<br>    }<br>}</pre><p>In the function above, it iscalling the lock function and getting a callback from the poolManager by using the lockAcquiredFill function encoded as an argument. Let’s take a look at the lockAcquiredFill function.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function lockAcquiredFill(PoolKey calldata key, int24 tickLower, int256 liquidityDelta)<br>    external<br>    selfOnly<br>    returns (uint128 amount0, uint128 amount1)<br>{<br>    BalanceDelta delta = poolManager.modifyPosition(<br>        key,<br>        IPoolManager.ModifyPositionParams({<br>            tickLower: tickLower,<br>            tickUpper: tickLower + key.tickSpacing,<br>            liquidityDelta: liquidityDelta<br>        }),<br>        ZERO_BYTES<br>    );<br>    if (delta.amount0() &lt; 0) poolManager.mint(key.currency0, address(this), amount0 = uint128(-delta.amount0()));<br>    if (delta.amount1() &lt; 0) poolManager.mint(key.currency1, address(this), amount1 = uint128(-delta.amount1()));<br>}</pre><p>Since the lockAcquiredFill function fulfills limit orders, it removes liquidity from the pool that users have put in. This is similar to the decreaseLiquidity function in the <a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">previous article</a> of “Limit Orders in V3”, i.e. it doesn’t withdraw, but modifyPosition.</p><p>The delta value of the token being removed from the poolManager contract will be negative. Now, should we use the “take” function to get the token back and make the delta value zero? We’re not doing that here, which means we’re not doing the “collect” from the <a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">previous article</a> of “Limit Orders in V3”. Then how do we get out of the lock? V4 utilizes ERC1155, which was not in V3. The “if” statement specifies that if the delta value is negative, it will mint an amount of ERC1155 tokens to the limitOrder contract address, which is itself.</p><p>Let’s look at the mint function in v4-core/contracts/PoolManager.sol.</p><pre>/// @inheritdoc IPoolManager<br>function mint(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>    _accountDelta(currency, amount.toInt128());<br>    _mint(to, currency.toId(), amount, &#39;&#39;);<br>}</pre><p>The _accountDelta function adds the amount to the delta value to make the delta equal to 0. Then, it mints ERC1155. ERC1155 can be minted multiple with the same token address as the id value as shown above. Unlike ERC721, ERC1155 tokens with the same id are fungible.</p><p>In this way, even if the value owed by the poolManager to the hook contract or user is not immediately taken by the hook contract or user, it is guaranteed to be withdrawn later by minting and holding ERC1155 tokens. It is also stated in the Uniswap V4 whitepaper that it is called ERC1155 Accounting as it can handle accounting between poolManager and users without transferring tokens.</p><p>And v4-periphery/contracts/hooks/examples/LimitOrder.sol implements the onERC1155Received function.</p><pre>function onERC1155Received(address, address, uint256, uint256, bytes calldata) external view returns (bytes4) {<br>    if (msg.sender != address(poolManager)) revert NotPoolManagerToken();<br>    return IERC1155Receiver.onERC1155Received.selector;<br>}</pre><p>These non-EOA contracts must implement onERC1155Received in order to receive ERC1155 tokens. By standard, contracts that do not implement onERC1155Received cannot receive ERCC1155 tokens.</p><p>The onERC1155Received function above checks if msg.sender is a poolManager, which prevents from maliciously obtaining ERC1155 tokens elsewhere and withdrawing the poolManager’s tokens.</p><h3>Withdraw</h3><p>The following is a sequence diagram of the Withdraw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*LIaUwVhnMueKQfAl.png" /><figcaption>Withdraw, Sequence Diagram</figcaption></figure><p>Let’s look at the withdraw function in v4-periphery/contracts/hooks/examples/LimitOrder.sol.</p><pre>function withdraw(Epoch epoch, address to) external returns (uint256 amount0, uint256 amount1) {<br>    EpochInfo storage epochInfo = epochInfos[epoch];<br>    if (!epochInfo.filled) revert NotFilled();<br><br>    uint128 liquidity = epochInfo.liquidity[msg.sender];<br>    if (liquidity == 0) revert ZeroLiquidity();<br>    delete epochInfo.liquidity[msg.sender];<br><br>    uint256 token0Total = epochInfo.token0Total;<br>    uint256 token1Total = epochInfo.token1Total;<br>    uint128 liquidityTotal = epochInfo.liquidityTotal;<br><br>    amount0 = FullMath.mulDiv(token0Total, liquidity, liquidityTotal);<br>    amount1 = FullMath.mulDiv(token1Total, liquidity, liquidityTotal);<br><br>    epochInfo.token0Total = token0Total - amount0;<br>    epochInfo.token1Total = token1Total - amount1;<br>    epochInfo.liquidityTotal = liquidityTotal - liquidity;<br>    poolManager.lock(<br>        abi.encodeCall(this.lockAcquiredWithdraw, (epochInfo.currency0, epochInfo.currency1, amount0, amount1, to))<br>    );<br><br>    emit Withdraw(msg.sender, epoch, liquidity);<br>}</pre><p>The above function gets the liquidity value of the withdrawing user, divides it by liquidityTotal and multiplies it by tokenTotal to withdraw the proportional amount. It then updates the epochInfo variable.</p><p>As always, it calls the lock function of the poolManager contract and interacts with the poolManager contract via the lockAcquiredWithdraw function.</p><p>Let’s look at the lockAcquiredWithdraw function in v4-periphery/contracts/hooks/examples/LimitOrder.sol.</p><pre>function lockAcquiredWithdraw(<br>    Currency currency0,<br>    Currency currency1,<br>    uint256 token0Amount,<br>    uint256 token1Amount,<br>    address to<br>) external selfOnly {<br>    if (token0Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency0))), token0Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency0, to, token0Amount);<br>    }<br>    if (token1Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency1))), token1Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency1, to, token1Amount);<br>    }<br>}</pre><p>Here, it transfers an amount of ERC1155 tokens equal to tokenAmount to withdraw to the poolManager contract and call the take function.</p><p>You may remember the take function from swap. The withdrawer must make the delta value of the token negative in the poolManager so that it can be withdrawn by calling the “take” function. Withdrawer can make the delta negative by transferring the ERC1155 token to the poolManager contract. Since PoolManager is also a contract, they implemented onERC1155Received. Let’s look at that function.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function onERC1155Received(address, address, uint256 id, uint256 value, bytes calldata) external returns (bytes4) {<br>    if (msg.sender != address(this)) revert NotPoolManagerToken();<br>    _burnAndAccount(CurrencyLibrary.fromId(id), value);<br>    return IERC1155Receiver.onERC1155Received.selector;<br>}<br><br>function _burnAndAccount(Currency currency, uint256 amount) internal {<br>    _burn(address(this), currency.toId(), amount);<br>    _accountDelta(currency, -(amount.toInt128()));<br>}</pre><p>The PoolManager burns the ERC1155 it received and uses the _accountDelta function to make the token’s delta value negative and increments the nonzeroDeltaCount by one. Then, withdrawer withdraws the token through the “take” function, which we covered in “swap” section, and set the delta value and nonzeroDeltaCount to 0 to get out of the lock.</p><p>This is how I analyzed UniswapV4 in general and limit orders in particular. Now let’s move on to testing on real data.</p><h3>Setting up a hook contract test in the Foundry environment</h3><p>First of all, the Uniswap V4 code is developed in the Foundry framework environment, and an example of the test code is publicly available. In this section, we’ll cover setting up a development environment to develop hook contracts. Before we get started, you’ll need to download Foundry. You can follow this <a href="https://book.getfoundry.sh/getting-started/installation">Foundry Docs</a> guide to download it.</p><p>Next, create a directory and run the following commands to set up your Foundry environment.</p><pre>forge init .</pre><p>If you get an error like this…</p><pre>Error: <br>Cannot run `init` on a non-empty directory.</pre><p>Add --force to the end of the command.</p><p>If you look at the folders and files after the command is executed, you can see the Counter.sol file in the src folder and a simple test code in the test folder. Also, a library called forge-std is downloaded along with it.</p><p>Let’s download the v4-periphery package which contains the BaseHook contract.</p><pre>forge install https://github.com/Uniswap/periphery-next</pre><p>This command will clone the GitHub repository of v4-periphery to the lib folder. You can then import the contract. In a foundry environment, the contract files are imported from the lib folder, not from node_modules. Let’s import the BaseHook contract.</p><pre>import {BaseHook} from &quot;../lib/periphery-next/contracts/BaseHook.sol&quot;;</pre><p>To omit the prefixes ../lib and /contracts, you can set up something called remappings in the foundry environment. Run the following command</p><pre>forge remappings</pre><p>result</p><pre>@ensdomains/=lib/periphery-next/lib/v4-core/node_modules/@ensdomains/<br>@openzeppelin/=lib/periphery-next/lib/openzeppelin-contracts/<br>@uniswap/v4-core/=lib/periphery-next/lib/v4-core/<br>ds-test/=lib/forge-std/lib/ds-test/src/<br>erc4626-tests/=lib/periphery-next/lib/openzeppelin-contracts/lib/erc4626-tests/<br>forge-gas-snapshot/=lib/periphery-next/lib/forge-gas-snapshot/src/<br>forge-std/=lib/forge-std/src/<br>hardhat/=lib/periphery-next/lib/v4-core/node_modules/hardhat/<br>openzeppelin-contracts/=lib/periphery-next/lib/openzeppelin-contracts/<br>openzeppelin/=lib/periphery-next/lib/openzeppelin-contracts/contracts/<br>periphery-next/=lib/periphery-next/contracts/<br>solmate/=lib/periphery-next/lib/solmate/src/<br>v4-core/=lib/periphery-next/lib/v4-core/contracts/</pre><p>The foundry will refer to the lib folder and automatically output the remappings. Note that the third line from the end says that periphery-next is the same as lib/periphery-next/contracts. Create a remappings.txt file in your root folder and paste the console output into it. You can then modify the import statement to look like this</p><pre>import {BaseHook} from &quot;periphery-next/BaseHook.sol&quot;;</pre><p>In this environment, you can develop hook contracts, write test code, and test them. See v4-periphery/hooks/examples/LimitOrder.sol for the limit order hook contract and v4-periphery/test/LimitOrder.t.sol for the test code.</p><p>“beforeEach” in the Mocha test environment is “setUp” in the Foundry. The setUp function is called before each test case is executed. The setUp code looks like this</p><pre>function setUp() public {<br>    initializeTokens();<br>    token0 = TestERC20(Currency.unwrap(currency0));<br>    token1 = TestERC20(Currency.unwrap(currency1));<br>    manager = new PoolManager(500000);<br>    ...<br>}</pre><p>When we first create the PoolManager contract, we pass 500000 as an argument. That value is initialized by assigning it to a variable called “controllerGasLimit” in Fees.sol, which PoolManager inherits from. The controllerGasLimit is used in the _fetchPorotoclFees function of Fees.sol.</p><p>v4-core/contracts/Fees.sol</p><pre>function _fetchProtocolFees(<br>    PoolKey memory key<br>) internal view returns (uint8 protocolSwapFee, uint8 protocolWithdrawFee) {<br>    if (address(protocolFeeController) != address(0)) {<br>        // note that EIP-150 mandates that calls requesting more than 63/64ths of remaining gas<br>        // will be allotted no more than this amount, so controllerGasLimit must be set with this<br>        // in mind.<br>        if (gasleft() &lt; controllerGasLimit) revert ProtocolFeeCannotBeFetched();<br>        try protocolFeeController.protocolFeesForPool{gas: controllerGasLimit}(key) returns (<br>            uint8 updatedProtocolSwapFee,<br>            uint8 updatedProtocolWithdrawFee<br>        ) {<br>            protocolSwapFee = updatedProtocolSwapFee;<br>            protocolWithdrawFee = updatedProtocolWithdrawFee;<br>        } catch {<br>            console.log(&#39;what!?&#39;);<br>        }<br><br>        _checkProtocolFee(protocolSwapFee);<br>        _checkProtocolFee(protocolWithdrawFee);<br>    }<br>}</pre><p>First, it checks to see if the “protocolFeeController” is set. Only the owner can set the “protocolFeeController” to any address, which will probably be determined by a governance vote. And when we call the “protocolFeesForPool” function of the “protocolFeeController” that returns “protocolSwapFee” and “protocolWithdrawFee”, we specify the gas as “controllerGasLimit” to prevent more gas from being used in that function.</p><p>EIP-150 requires that you do not allocate more than 63/64 of the remaining gas (gasLeft()), so you need to set the “controllerGasLimit” with that in mind. The official Solidity documentation does not recommend explicitly specifying a gas value for an opcode, as it may change in the future, but this is how it is implemented, and I don’t even see an onlyOwner function that allows owner to change the “controllerGasLimit” state. If the gas cost of an opcode changes in the future and the “protocolFeesForPool” function of the “protocolFeeController” can no longer be called, the “protocolFeeController” address will need to be set up anew.</p><p>You can find an example of the protocolFeesForPool function in v4-core/contracts/test/ProtocolFeeControllerTest.sol.</p><pre>function protocolFeesForPool(PoolKey memory key) external view returns (uint8, uint8) {<br>    return (swapFeeForPool[key.toId()], withdrawFeeForPool[key.toId()]);<br>}</pre><p>For this function, 500000 gas seems to be sufficient, and since they are currently setting controllerGasLimit to 500000 in all test code examples in v4-periphery, we will use this value.</p><p>The “_fetchPorotoclFees” function is used in the “initialize” and “setProtocolFees” functions of the PoolManager contract. Pools that are initialized before the protocol fee is set can be set using the setProtocolFees function.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function setProtocolFees(PoolKey memory key) external {<br>    (uint8 newProtocolSwapFee, uint8 newProtocolWithdrawFee) = _fetchProtocolFees(key);<br>    PoolId id = key.toId();<br>    pools[id].setProtocolFees(newProtocolSwapFee, newProtocolWithdrawFee);<br>    emit ProtocolFeeUpdated(id, newProtocolSwapFee, newProtocolWithdrawFee);<br>}</pre><p>Since there will be so many pools, they’ve made it so that anyone can run it at the expense of gas.</p><p>Let’s continue to finalize the setUp function.</p><p>In the <a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">previous post</a>, “Hook Contract Setup and CREATE2 Deployment”, I mentioned that we need to set the first 8 bits of the hook contract to a specific bit to deploy the hook contract using CREATE2. There is a way to test in the Foundry environment without doing this.</p><p>First, the LimitOrder contract has true flags for “afterInitialize” and “afterSwap”.</p><p>AFTER_INITIALIZE_FLAG</p><p>⇒ 1 &lt;&lt; 158 ⇒ 2¹⁵⁸</p><p>⇒ to hex ⇒ 4000000000000000000000000000000000000000 (39 zeros)</p><p>AFTER_SWAP_FLAG</p><p>⇒ 1&lt;&lt;154 ⇒ 2¹⁵⁴</p><p>⇒ to hex ⇒ 400000000000000000000000000000000000000 (38 zeros)</p><p>Therefore, the address of the LimitOrder contract should start with 0x44, and in our test, we can set it to 0x4400000000000000000000000000000000000000000000000000 without any problem.</p><p>So, let’s create the LimitOrder variable in the test code as follows.</p><pre>LimitOrder limitOrder = LimitOrder(address(0x4400000000000000000000000000000000000000));</pre><p>In the above, there is no “new” keyword, so it is not a contract, just a variable of type LimitOrder.</p><p>Then let’s override the validateHookAddress function to make it an empty function and create a contract called LimitOrderImplementation that inherits from the LimitOrder contract. It looks like this.</p><p>test/shared/implementation/LimitOrderImplementation.sol</p><pre>contract LimitOrderImplementation is LimitOrder {<br>    constructor(IPoolManager _poolManager, LimitOrder addressToEtch) LimitOrder(_poolManager) {<br>        Hooks.validateHookAddress(addressToEtch, getHooksCalls());<br>    }<br><br>    // make this a no-op in testing<br>    function validateHookAddress(BaseHook _this) internal pure override {}<br>}</pre><p>The reason for this is to avoid modifying the existing LimitOrder contract’s valdiateHookAddress function, just for testing purposes.</p><p>Next, in the setUp function, we can set up the limitOrder contract like this</p><pre>function setUp() public {<br>  ...<br>  vm.record();<br>    LimitOrderImplementation impl = new LimitOrderImplementation(manager, limitOrder);<br>    (, bytes32[] memory writes) = vm.accesses(address(impl));<br>    vm.etch(address(limitOrder), address(impl).code);<br>    // for each storage key that was written during the hook implementation, copy the value over<br>    unchecked {<br>        for (uint256 i = 0; i &lt; writes.length; i++) {<br>            bytes32 slot = writes[i];<br>            vm.store(address(limitOrder), slot, vm.load(address(impl), slot));<br>        }<br>    }<br>...</pre><p>vm.record</p><ul><li>Instruction to start recording all storage reads and writes.</li><li>LimitOrderImplementation impl = new LimitOrderImplementation(manager, limitOrder) *recording storage writes</li></ul><p>(, bytes32[] memory writes) = vm.accesses(address(impl));</p><ul><li>In the writes array, we can get all the storage slots that LimitOrderImplementation wrote to.</li></ul><p>vm.etch(address(limitOrder), address(impl).code);</p><ul><li>Append the LimitOrderImplementation.sol code to the address 0x4400000000000000000000000000000000000000000000000000.</li></ul><p>The “for” loop</p><ul><li>The storage writes(e.g. poolManager address) that were made when deploying the LimitOrderImplementation are applied to the limitOrder address. This is done by using vm.load to get the value in the slot corresponding to the slot value of the impl and store it in the same slot.</li></ul><p>This way, in the Foundry environment, we can attach code to any address and manipulate the slot without creating a contract.</p><p>Let’s continue with the setUp function.</p><pre>function setUp() public {<br>  ...<br>  key = PoolKey(currency0, currency1, 3000, 60, limitOrder);<br>  id = key.toId();<br>    manager.initialize(key, SQRT_RATIO_1_1, ZERO_BYTES);<br>  ...</pre><p>We declare a key value of 3000 for the Fee, 60 for the tickSpacing, and a hook for the LimitOrder contract, and deploy the pool via the initialize function of the PoolManager contract.</p><p>When we deploy the pool, we pass the key value, SQRT_RATIO_1_1, and ZERO_BYTES as arguments.</p><p>SQRT_RATIO_1_1 is 79228162514264337593543950336.</p><p>In Uniswap, tick is a finite integer and can be both positive and negative. When storing a price, we store the sqrt(price) as a fixed-point number called <a href="https://en.wikipedia.org/wiki/Q_%28number_format%29">Q64.96</a>, which is a rational number with 64 bits for the integer part and 96 bits for the fractional part.<br>For example, assuming that token x has a reserve of 3 and token y has a reserve of 5, the process to convert x’s price to sqrtPriceX96 is as follows</p><p>In our test case, for simplicity’s sake, we’ll assume that the reserve is 1:1 and set the price to sqrt(1/1)*2⁹⁶ which is SQRT_RATIO_1_1. The last argument value is the value that will be passed to the callback function when the hook flag is checked and callbacked, which we will set to 0 since we don’t need it in this test case.</p><p>The “initialize” of the PoolManager was covered in the “Creating a Pool” section in the <a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">previous article</a>. After calling the PoolManager’s initialize function, the result is as follows</p><p>slot0 = Slot0({</p><p>sqrtPriceX96: 79228162514264337593543950336,</p><p>tick: 0,</p><p>protocolSwapFee: 0,</p><p>hookSwapFee: 0,</p><p>protocolWithdrawFee: 0,</p><p>hookWithdrawFee: 0</p><p>});</p><p>The tick can be obtained by the following formula.</p><p>tick = log(sqrtPriceX96 / ²⁹⁶)</p><p>=&gt; log(79228162514264337593543950336 / 2⁹⁶) ⇒ 0</p><p>The setUp function concludes like below.</p><pre>function setUp() public {<br>  ...    <br>  swapRouter = new PoolSwapTest(manager);<br><br>    token0.approve(address(limitOrder), type(uint256).max);<br>    token1.approve(address(limitOrder), type(uint256).max);<br>    token0.approve(address(swapRouter), type(uint256).max);<br>    token1.approve(address(swapRouter), type(uint256).max);<br>}</pre><p>For SwapRouter, you can currently use v4-core/contracts/test/PoolSwapTest.sol. The test setup is done by approving the limitOrder and swapRouter contracts beforehand in order to place a limit order.</p><h3>Testing Limit Orders</h3><p>With the test environment set up, it’s time to test the limit order. We have kept the test scenario as simple as possible and refer to v4-periphery/test/LimitOrder.t.sol. We’ll be testing the following sequence: place a limit order ⇒ swap ⇒ withdrawal.</p><p>We’ve covered the code for each scenario in detail before, so we’ll only cover how the state changes based on real data. Note that the poolManager manages states in a State struct for each pool.</p><p>v4-core/contracts/libraries/Pool.sol</p><pre>struct State {<br>    Slot0 slot0;<br>    uint256 feeGrowthGlobal0X128;<br>    uint256 feeGrowthGlobal1X128;<br>    uint128 liquidity;<br>    mapping(int24 =&gt; TickInfo) ticks;<br>    mapping(int16 =&gt; uint256) tickBitmap;<br>    mapping(bytes32 =&gt; Position.Info) positions;<br>}</pre><h4>place a limit order</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5RSH8C023Y05RErZ.png" /><figcaption>placing a limit order, this illustration is a summary that completely omits the intermediate steps, so please refer to the following</figcaption></figure><pre>function testLimitOrder() public {<br> int24 tickLower = 0;<br> bool zeroForOne = true;<br> uint128 liquidity = 1000000;<br> limitOrder.place(key, tickLower, zeroForOne, liquidity);<br> ...</pre><p>(modifyPoistion ⇒ transferFrom ⇒ settle)</p><p>(1) modifyPoistion</p><p>— PoolManager —</p><p>If tickLower is 0 and zeroForOne is true, the tick range will be 0 to 0+tickSpacing. We will provide 1000000 liquidity in the range of 0 to 60 ticks. Since the current tick is 0, we will only provide liquidity with token0.</p><p>feeGrowthGlobal0x128 = 0<br>feeGrowthGlobal1x128 = 0<br>liquidity = 1000000</p><p>updateTick</p><ul><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li></ul><p>tickBitmap.flipTick</p><ul><li>tickBitmap[0] = …00011 (binary, 254 zeros)</li><li>tickBitmap is a 256-bit mapping variable and each value is a word, and the index in tickBitmap[index] is wordPos. Each position in a word is called a bitPos. The bitPos starts at 0 and increments leftward to 255.</li></ul><p>position update</p><ul><li>positions[keccak256(abi.encodePacked(limit order hook address, 0, 60))] = { liquidity : 1000000, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 0 }</li></ul><p>return delta.amount0 = 2996</p><ul><li>2996 is the value obtained by the getAmount0Delta function in v4-core/contracts/libraries/SqrtPriceMath.sol.</li><li>amount0Delta = (Liquidity * ²⁹⁶) * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / UpperSqrtPriceX96 / LowerSqrtPriceX96</li><li>= (1000000 * 79228162514264337593543950336) * (79466191966197645195421774833–79228162514264337593543950336 ) / 79466191966197645195421774833 / 79228162514264337593543950336</li><li>= 2996</li></ul><p>(2) transferFrom</p><p>user transfers 2996 token0 to poolManager</p><p>(3) settle</p><p>reservesOf[token0] = 2996</p><p><strong>Delta Value Change </strong>(modifyPosition + transferFrom &amp; settle)</p><p>modifyPosition</p><ul><li>currencyDelta[limit order hook address][token0Address] = 2996</li><li>nonzeroDeltaCount increases from 0 to 1</li></ul><p>transferFrom &amp; settle</p><ul><li>currencyDelta[limit order hook address][token0Address] = 2996–2996 = 0</li><li>nonzeroDeltaCount decreases from 1 to 0</li></ul><p>— LimitOrder —</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false,</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total:0,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>After placing the limit order, you can proceed to assertion testing like this.</p><pre>function testLimitOrder() public {<br>  ...<br>  assertTrue(<br>      EpochLibrary.equals(<br>          limitOrder.getEpoch(key, tickLower, zeroForOne),<br>          Epoch.wrap(1)<br>      )<br>  );<br>  assertEq(<br>      manager.getLiquidity(<br>          id,<br>          address(limitOrder),<br>          tickLower,<br>          tickLower + 60<br>      ),<br>      liquidity<br>  );<br>  ...<br>}</pre><p>Note that epoch stores values starting at 1.</p><h4>Swap &amp; SwapAfter</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*eIo1IPSHzjVzmB4B.png" /><figcaption>Swap, this illustration is a summary that completely omits the intermediate steps, so please refer to the following</figcaption></figure><pre>function testLimitOrder() public {<br> ...<br> swapRouter.swap(<br>            key,<br>            IPoolManager.SwapParams(<br>                false,<br>                1e18,<br>                TickMath.getSqrtRatioAtTick(60)<br>            ),<br>            PoolSwapTest.TestSettings(true, true)<br>        );</pre><p>The swapRouter calls the PoolManager’s lock function.</p><p>The SwapParams can be found in v4-core/contracts/interfaces/IPoolManager.sol and look like this.</p><pre>struct SwapParams {<br>    bool zeroForOne;<br>    int256 amountSpecified;<br>    uint160 sqrtPriceLimitX96;<br>}</pre><p>Since zeroForOne is false, we are swapping token1 for token0. We set amountSpecified to 1e18, and there are currently only 2996 token0s in the pool. Since we set sqrtPriceLimitX96 to getSqrtRatioAtTick(60), we will not transfer all 1e18 (since there is not as much liquidity between 0 and 60 as 1e18), and a partial swap will occur.</p><p>The TestSettings can be found at v4-core/contracts/test/PoolSwapTest.sol.</p><pre>struct TestSettings {<br>    bool withdrawTokens;<br>    bool settleUsingTransfer;<br>}</pre><p>Setting “withdrawTokens” to true will mint ERC1155 without “take”. false does the opposite.</p><p>If “settleUsingTransfer” is set to true, it will settle with token transferFrom, and if set to false, it will transfer ERC1155 to PoolManager.</p><p>For this test, we set both to true.</p><p>— PoolManager —</p><p>tickBitmap.nextInitializedTickWithinOneWord</p><p>v4-core/contracts/libraries/TickBitmap.sol</p><pre>function nextInitializedTickWithinOneWord(<br>    mapping(int16 =&gt; uint256) storage self,<br>    int24 tick,<br>    int24 tickSpacing,<br>    bool lte<br>) internal view returns (int24 next, bool initialized) {<br>    unchecked {<br>        int24 compressed = tick / tickSpacing;<br>    ...<br>    (int16 wordPos, uint8 bitPos) = position(compressed + 1);<br>        // all the 1s at or to the left of the bitPos<br>        uint256 mask = ~((1 &lt;&lt; bitPos) - 1);<br>        uint256 masked = self[wordPos] &amp; mask;<br><br>...<br>function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {<br>    unchecked {<br>        wordPos = int16(tick &gt;&gt; 8);<br>        bitPos = uint8(int8(tick % 256));<br>    }<br>}</pre><p>This mask operation finds the next initialized tick. Since zeroForOne is true and token0’s price is increasing, we need to find a larger tick.</p><p>Current tick: 0, word:0, bitPos:1</p><ul><li>comprssed is 0/60 = 0. Then we add 1 to compressed, so that wordPos is 0 and bitPos is 1. The reason for the addition of 1 is that the current bitPos value is excluded when looking for a larger bitPos value.</li></ul><p>Current tickBitmap value: tickBitmap[0] = …00011 (binary, 254 zeros)</p><ul><li>Since zeroForOne is true, we find a tick initialized from the left including itself, based on the current 1 bitPos. The mask is ~((1 &lt;&lt; bitPos) — 1) ⇒ 111….1110 and we can use the wordPos &amp; mask operation to find a tick that is initialized in the same word, which is 1 bitPos. Multiplying 1 bitPos by 60 tickSpacing gives us a tickNext value of 60.</li></ul><p>computeSwapStep</p><ul><li>amountIn = RoundingUp(Liquidity * (UpperSqrtPriceX96 — LowerSqrtPriceX96) /2⁹⁶) <br>=&gt; 1000000 * (79466191966197645195421774833–79228162514264337593543950336) / 2⁹⁶ = 3005</li><li>amountOut = (Liquidity *2⁹⁶) * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / UpperSqrtPriceX96 / LowerSqrtPriceX96<br>=&gt; (1000000 *2⁹⁶) * (79466191966197645195421774833–79228162514264337593543950336) / 79466191966197645195421774833 / 79228162514264337593543950336 = 2995</li><li>feeAmount = RoundingUp(amountIn * 3000 / (1000000–3000)) = 10</li><li>feeGrowthGlobal1X128 = feeAmount *2¹²⁸ / liquidity = 3402823669209384634633746074317682</li><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }<br>=&gt; ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 3402823669209384634633746074317682 }</li></ul><p><strong>Delta Value Change </strong>(swap)</p><ul><li>currencyDelta[swapRouter address][token0Address] = -2995</li><li>currencyDelta[swapRouter address][token1Address] = 3015</li><li>nonzeroDeltaCount increases from 0 to 2</li></ul><p>Call the AfterSwap hook function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Tp4XwD20wd5KlJli.png" /><figcaption>AfterSwap, this illustration is a summary that completely omits the intermediate steps, so please refer to the following</figcaption></figure><p>The LimitOrder contract calls the PoolManager’s “lock” function.</p><p>Remove liquidity by 1000000(EpochInfos[epochs[keccack256(abi.encode(key,0,true))]].liquidityTotal) in the range 0 to 60 ticks via modifyPosition of lockAcquiredFilled.</p><p>— PoolManager —</p><p>feeGrowthGlobal0x128 = 0</p><p>feeGrowthGlobal1x128 = 0 ⇒ 3402823669209384634633746074317682</p><p>liquidity = 1000000 ⇒ 0</p><p>updateTick</p><ul><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }<br>⇒ ticks[0]: { liquidityGross: 0, liquidityNet:0, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }<br>=&gt; ticks[60]: { liquidityGross: 0, liquidityNet: 0, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 3402823669209384634633746074317682 }</li></ul><p>tickBitmap.flipTick</p><ul><li>tickBitmap[0] = …00011 (binary, 254 zeros) ⇒ …00000 (256 zeros)</li></ul><p>position update</p><ul><li>positions[keccak256(abi.encodePacked(limit order hook address, 0, 60))] = { liquidity : 1000000, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 0 }<br>⇒ positions[keccak256(abi.encodePacked(limit order hook address, 0, 60))] = { liquidity : 0, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 3402823669209384634633746074317682 }</li></ul><p>feesOwed = 9</p><ul><li>feesOwed1 = (feeGrowthInside1x128 — _self.feeGrowthInside1LastX128) * liquidity / 2¹²⁸<br>= (3402823669209384634633746074317682–0) * 1000000 / 340282366920938463463374607431768211456 = 9</li></ul><p>return delta.amount1 = -3004 + (-9) = -3013</p><ul><li>delta.amount1 = -(Liquidity * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / 2⁹⁶) + (-feesOwed)</li><li>= -(1000000 * (79466191966197645195421774833–79228162514264337593543950336 ) / 79228162514264337593543950336) + (-9) = -3013</li></ul><p>— LimitOrder —</p><p>ERC1155 mint</p><p>ERC1155 mint by 3013 to LimitOrder address</p><p><strong>Delta Value Change </strong>(modifyPosition + mint ERC1155)</p><p>modifyPosition</p><ul><li>currencyDelta[limit order hook address][token1Address] = -3013</li><li>nonzeroDeltaCount는 increases from 2 to 3</li></ul><p>mint ERC1155</p><ul><li>currencyDelta[limit order hook address][token0Address] = -3013 + 3013 = 0</li><li>nonzeroDeltaCount decreases from 3 to 2</li></ul><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false, ⇒ true</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total: 0 ⇒ 3013,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>Finalizing the Swap</p><p>take (token0)</p><ul><li>reservesOf[token0] = 2996–2995 = 1</li><li>currencyDelta[swapRouter address][token0Address] = -2995 + 2995 = 0</li><li>nonzeroDeltaCount decreases from 2 to 1</li><li>transfer to swapper</li></ul><p>transfer token1 to PoolManager</p><ul><li>reservesOf[token1] = 3015</li></ul><p>settle token1</p><ul><li>currencyDelta[swapRouter address][token1Address] = 3015–3015 = 0</li><li>nonzeroDeltaCount decreases from 1 to 0</li></ul><p>Once the swap is done, you can proceed to assertion testing like this.</p><pre>function testLimitOrder() public {<br>  ...<br>  assertEq(limitOrder.getTickLowerLast(id), 60);<br>  (, int24 tick, , , , ) = manager.getSlot0(id);<br>  assertEq(tick, 60);<br>  <br>  (<br>      bool filled,<br>      ,<br>      ,<br>      uint256 token0Total,<br>      uint256 token1Total,<br>  <br>  ) = limitOrder.epochInfos(Epoch.wrap(1));<br>  assertTrue(filled);<br>  assertEq(token0Total, 0);<br>  assertEq(token1Total, 3013);<br>  assertEq(<br>      manager.getLiquidity(<br>          id,<br>          address(limitOrder),<br>          tickLower,<br>          tickLower + 60<br>      ),<br>      0<br>  );<br>  ...<br>}</pre><h4>Withdraw</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*4zpeQLH4jGJHrJvu.png" /><figcaption>Withdraw, this illustration is a summary that completely omits the intermediate steps, so please refer to the following</figcaption></figure><pre>function testLimitOrder() public {<br> ...<br> limitOrder.withdraw(Epoch.wrap(1), &lt;address to receive&gt;);<br> ...</pre><p>The first argument is the epcoh index and the second argument is the address to receive.</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false, ⇒ true</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total: 0 ⇒ 3013 ⇒ 3013–3013 = 0</p><p>liquidityTotal:1000000 ⇒ 1000000–1000000 = 0</p><p>liquidity[msg.sender]:1000000 ⇒ delete liquidity[msg.sender] ⇒ 0</p><p>}</p><p>ERC1155 safeTransferFrom</p><ul><li>The LimitOrder contract sends 3013 ERC1155 tokens to the PoolManager.</li><li>The PoolManager burns all the ERC1155 tokens received.</li><li>currencyDelta[limit order hook address][token0Address] = -3013</li><li>nonzeroDeltaCount increases from 0 to 1</li></ul><p>Take</p><ul><li>reservesOf[token1] = 3015–3013 = 2</li><li>nonzeroDeltaCount decreases from 1 to 0</li><li>transfers 3013 token1 from poolManager to &lt;receiver address&gt;</li></ul><p>Once we’re done with the withdrawal, we can proceed with the assertion test like this.</p><pre>function testLimitOrder() public {<br>  ...<br>  (, , , token0Total, token1Total, ) = limitOrder.epochInfos(<br>      Epoch.wrap(1)<br>  );<br>  <br>  assertEq(token0Total, 0);<br>  assertEq(token1Total, 0);<br>}</pre><p>Finished the test.</p><p>There’s a lot I haven’t covered yet in Uniswap V4. I’ll conclude with a quick look at EIP-1153 Transient Storage.</p><h3>EIP-1153: Transient Storage</h3><p>EIP-1153 is included in the scope of the Ethereum “Dencun” upgrade in January 2024, and the Uniswap V4 whitepaper states that it will use Transient Storage to reduce gas costs. I’ll cover this briefly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*U3trUhYXQjfz0wc3.png" /><figcaption>Source: <a href="https://twitter.com/pcaversaccio">Pascal Marco Caversaccio</a></figcaption></figure><p>In addition to the existing “Calldata”, “Memory”, or “Storage”, Transient Storage is introduced as shown above. Transient Storage is volatile at the end of the transaction like “memory”, and can be read and written from the global scope like storage(world state).</p><p>There will be new opcodes “tload” and “tstore” for reading and writing, which are 95% cheaper than “sload” and “sstore”. This can be very useful in the following situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*H-zhYgbSwb2Wx7KO.png" /></figure><p>This is the delta value commonly used in Uniswap V4. The delta will eventually start at zero and end at zero. So there is no problem with it being volatile at the end of the transaction. And since the value is not just used within a single function, but across functions, it should have a global scope, just like world state. Therefore, it’s perfect to store delta values in Transient Storage. By eliminating unnecessary storage operations, we can save a lot of gas.</p><p>*In a future TONDEX project, we will work on migrating Uniswap V3 to V4. We will introduce a new fee policy that will greatly benefit liquidity providers using hook contracts, and we will continue to explore and develop ideas for new DeFi products.</p><p>I would like to close this article. Thanks for reading and feedback is welcome.</p><p>Reference</p><ul><li>Uniswap V4 Whitepaper (<a href="https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf">https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf</a>)</li><li>v4-core (<a href="https://github.com/Uniswap/v4-core">https://github.com/Uniswap/v4-core</a>)</li><li>v4-periphery (<a href="https://github.com/Uniswap/v3-periphery">https://github.com/Uniswap/v3-periphery</a>)</li><li>Uniswap Blog (<a href="https://blog.uniswap.org/uniswap-v4">https://blog.uniswap.org/uniswap-v4</a>)</li><li>EIP-1153 (<a href="https://eips.ethereum.org/EIPS/eip-1153">https://eips.ethereum.org/EIPS/eip-1153</a>)</li><li>Foundry Docs (<a href="https://book.getfoundry.sh/">https://book.getfoundry.sh/</a>)</li></ul><p>Thanks to Kevin, Zena for feedback on this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c130997a4481" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokamak-network/uniswap-v4-limit-order-hook-part-2-c130997a4481">Uniswap V4 Limit Order Hook part 2</a> was originally published in <a href="https://medium.com/tokamak-network">Tokamak Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap V4 Limit Order Hook part 1]]></title>
            <link>https://medium.com/tokamak-network/uniswap-v4-limit-order-hook-part-1-586233620584?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/586233620584</guid>
            <category><![CDATA[research]]></category>
            <category><![CDATA[tokamak-network]]></category>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[onther]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 07:32:35 GMT</pubDate>
            <atom:updated>2023-11-21T07:44:17.679Z</atom:updated>
            <content:encoded><![CDATA[<h4>Smart Contract Source Code Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zJInvpWKGMHeMx4N.png" /><figcaption>Uniswap V4 Logo (Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p>Uniswap V4 introduces hooks, which allow custom logic to be executed at various points in the interaction with Uniswap pools. The Uniswap V4 official blog lists dynamic fees, on-chain limit orders, and Time-weighted Automated Market Maker (TWAMM), which breaks large trades into smaller ones and processes them over a longer period of time, as examples of hooks. Uniswap Labs sees Uniswap as a financial infrastructure, not just a decentralized exchange (DEX), where custom plugins and processes can be created.</p><p>A project called TONDEX, which will eventually go live on the Titan mainnet, will use Uniswap V4’s hooks to implement limit orders. Draft versions of the Core and Periphery repositories are currently available on the Uniswap GitHub. Testing was done using the Foundry framework. In this article, we’ll read and analyze the code in the draft version to understand how limit orders are implemented on-chain and how it differs from V3.</p><p>*This article requires some understanding of Uniswap V3 to read.</p><ul><li>Korean version of the article can be found below:</li></ul><ul><li><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%ED%9B%85-part-1-1075a8c9e654">Uniswap V4 지정가 주문 훅 part 1</a></li><li><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%EB%B6%84%EC%84%9D-%EC%8B%9C%EB%A6%AC%EC%A6%88-part-2-6d46e01108a6">Uniswap V4 지정가 주문 훅 part 2</a></li></ul><p>The table of contents is as follows</p><ul><li>Limit orders in V3</li><li>V4 Contracts Overview</li><li>V4 Hook Flow</li><li>Hook contract setup and CREATE2 deployment</li><li>Creating a pool</li><li>Placing a limit order</li></ul><h3>Limit Orders in V3</h3><p>Before we dive into the code, let’s take a look at an illustrated example of how a limit order works in Uniswap V3.</p><p>(1) Current pool status</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HJ-F8c9FH2ugP2Jx.png" /></figure><p>Let’s say the current tick is 85176. The tick is equal to log_{sqrt(1.0001)}(sqrt(price)). In this graph, height represents liquidity, and the left side of the current tick is filled with USDC liquidity and the right side of the current tick is filled with ETH liquidity.</p><p>Now, the user expects ETH to go up in price. More specifically, he expects the tick to go above 85680. So he will provide liquidity in ETH for the tick range of 85620 to 85680. It will look like below.</p><p>(2) With liquidity in ETH in the range of 85620 to 85680</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6ITZF5hwNB99Sg7U.png" /></figure><p>Here, 85620 is the result of 85680–60. To understand why we subtracted 60, you need to know what “tickSpacing” is. If you go to the app to add liquidity in Uniswap V3, you’ll see the following fee tiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*deSCRISup79V6eUq.png" /></figure><p>Each value represents a fee for trading in that pool. And each value is matched with a tickSpacing, which is fixed.</p><p>0.01% Fee Tier ⇒ 1 TickSpacing</p><p>0.05% Fee Tier ⇒ 10 TickSpacing</p><p>0.3% Fee Tier ⇒ 60 TickSpacing (our example)</p><p>1% Fee Tier ⇒ 200 TickSpacing</p><p>TickSpacing is the tick interval that defines the distance between ticks. The wider the tickSpacing is, the more gas efficient but less accurate it is. Vice versa for shorter spacings. Ticks are indexed by multiples of tickSpacing to manage liquidity information. For accuracy reasons, the value of the current tick does not need to be a multiple of tickSpacing.</p><p>The 0.05%-1% Fee Tier and respective TickSpacing are hardcoded in <a href="https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/UniswapV3Factory.sol#L26-L31C34">v3-core/contracts/UniswapV3Factory.sol</a>, and the activation of the 0.01% fee tier was decided through a Uniswap governance vote.</p><p>(3) The tick is now up to 85680</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RfkhCUSYdGVfQTIU.png" /></figure><p>In the image above, there were a lot of swaps selling USDC and buying ETH, and the current tick has reached 85680 as expected. The ETH liquidity provided earlier will be replaced with USDC liquidity, and the USDC will be collected.</p><p>At this point, the user (EOA) encodes the “decreaseLiquidity” and “collect” functions in the v3-periphery/contracts/NonfungiblePositionManganager contract, sets them as arguments, and calls the Multicall function. Here’s a quick explanation of what each does.</p><p>If you look at v3-core/contracts/libraries/Position.sol, you can see the Info struct.</p><pre>// info stored for each user&#39;s position<br>struct Info {<br>    // the amount of liquidity owned by this position<br>    uint128 liquidity;<br>    // fee growth per unit of liquidity as of the last update to liquidity or fees owed<br>    uint256 feeGrowthInside0LastX128;<br>    uint256 feeGrowthInside1LastX128;<br>    // the fees owed to the position owner in token0/token1<br>    uint128 tokensOwed0;<br>    uint128 tokensOwed1;<br>}</pre><p>decreaseLiquidity</p><ul><li>Recalculates feeGrowthInsideLast based on the current tick and updates the tokensOwed value with the liquidity information. *tokensOwed is the collectable amount.</li></ul><p>collect</p><ul><li>This function claims as much as tokensOwed.</li></ul><p>However, the user must continue to monitor the tick change of the pool and manually call the “decreaseLiquidity” and “collect” functions. This is because smart contracts are not currently designed to watch other smart contracts and trigger transactions on their own. Or this can be done by using an off-chain bot.</p><p>However, in V4, they’ve made it possible to make limit orders completely on-chain using the limit order hook.</p><h3>V4 Contracts Overview</h3><p>Similar to V3, Uniswap V4 manages contracts in two repositories: <a href="https://github.com/Uniswap/v4-core">v4-core</a> and <a href="https://github.com/Uniswap/v4-periphery">v4-periphery</a>.</p><p>The overall contract structure is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ugf9XsqCwZz-GMLD.png" /></figure><p>In V4, unlike V3, a contract called PoolManager exists in the v4-core repository, and the logic for initialize, swap, and modifyPosition are all implemented in the v4-core/contracts/libraries/Pool.sol library. The PoolManager contract in v4-core is similar in some ways to the NonfungiblePositionManager contract in v3-periphery, but it stores the state used by all core logic.</p><p>And in V4, they make full use of User-defined Value Types. They defined each type in the “<a href="https://github.com/Uniswap/v4-core/tree/main/src/types">types</a>” folder. For example, they defined a User-defined Value Type called “Currency” to manage each token, instead of using the built-in value type “address”.</p><p>v4-core/contracts/types/Currency.sol</p><pre>type Currency is address;<br><br>using {greaterThan as &gt;, lessThan as &lt;, equals as ==} for Currency global;<br>function equals(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) == Currency.unwrap(other);<br>}<br>function greaterThan(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) &gt; Currency.unwrap(other);<br>}<br>function lessThan(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) &lt; Currency.unwrap(other);<br>}<br>/// @title CurrencyLibrary<br>/// @dev This library allows for transferring and holding native tokens and ERC20 tokens<br>library CurrencyLibrary {<br>    using CurrencyLibrary for Currency;<br>  ...</pre><p>When you define a type this way, it doesn’t have any member functions. Therefore, we cannot use basic operators such as &gt;, &lt;, and ==, so they implemented “equals”, “greaterThan”, and “lessThan” functions as shown above, and used the “using for global” keyword to make them available in global scope. In each function, you can convert the type from “Currency” to “address” through “unwrap”, and from “address” to “Currency” through “wrap”.</p><p>In v4-periphery, there are only hook contracts. These hook contracts all inherit from the abstract contract “BaseHook” and override unimplemented functions to fulfill them. They use the IPoolManager interface to interact with the PoolManager contract. This is not a complete repository yet, and there may be a “positionManager” contract for no hook pools like in V3.</p><h3>V4 Hook Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*oo42e3OulEqJPG3E.png" /><figcaption>(source: Uniswap V4 <a href="https://github.com/Uniswap/v4-core/tree/main/docs">Whitepaper</a>)</figcaption></figure><p>The figure above shows the flow for executing custom logic hooks before and after a swap. Before the swap, the beforeSwap hook is executed if the flag is checked and true, and after the swap, the afterSwap hook is executed if the afterSwap flag is checked and true to finish the swap.</p><p>You can really make any custom logic in the hook as long as the value of delta is zero (we’ll see what “delta” is later). Even malicious hooks can be developed and made into pools in V4.</p><p>Let’s take a look at the PoolKey struct in v4-core/contracts/types/PoolKey.sol.</p><pre>/// @notice Returns the key for identifying a pool<br>struct PoolKey {<br>    /// @notice The lower currency of the pool, sorted numerically<br>    Currency currency0;<br>    /// @notice The higher currency of the pool, sorted numerically<br>    Currency currency1;<br>    /// @notice The pool swap fee, capped at 1_000_000. The upper 4 bits determine if the hook sets any fees.<br>    uint24 fee;<br>    /// @notice Ticks that involve positions must be a multiple of tick spacing<br>    int24 tickSpacing;<br>    /// @notice The hooks of the pool<br>    IHooks hooks;<br>}</pre><p>In V3, pools were identified by three values: token0, token1 address, and fee. As explained above(“Limit Orders in V3&quot;), there are a total of 4 fee tiers, each matched to a TickSpacing and fixed. Therefore, it was possible to create up to 4 pools with the same token0 and token1.</p><p>In V4, it’s different. The fee and tickSpacing are not a set, and a variable “hooks” has been added. This means that there are a total of 5 values that identify pools, therefore an infinite number of pools can be created. For example, a tickSpacing of 61 is possible.</p><p>Currently, the smart-order-router finds the best path for the swap, as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*IA76QaqUGGpWZgze.png" /><figcaption>Multipath on Uniswap V3 Swap</figcaption></figure><p>However, with the upgrade to V4, there will be pools with malicious hooks, and it will be too inefficient to calculate the amountOut of a swap across a vast number of pools with different hooks. We expect that there will be some policy to support only pools with no hooks (which is still too many), or only pools with hooks that have been developed and audited by a trusted organization. We also expect that <a href="https://blog.uniswap.org/how-uniswapv4-uniswapx-work-together">UniswapX</a> will be heavily utilized.</p><h3>Hook contract setup and CREATE2 deployment</h3><p>Before we dive into limit orders, let’s take a look at which flags to set in the hook contract and how to set them.</p><p>As mentioned above, all hook contracts inherit from the abstract contract BaseHook and implement it by overriding unimplemented functions. One such function is “getHooksCalls”. Let’s look at this function in the limit order contract first.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function getHooksCalls() public pure override returns (Hooks.Calls memory) {<br>    return Hooks.Calls({<br>        beforeInitialize: false,<br>        afterInitialize: true,<br>        beforeModifyPosition: false,<br>        afterModifyPosition: false,<br>        beforeSwap: false,<br>        afterSwap: true,<br>        beforeDonate: false,<br>        afterDonate: false<br>    });<br>}</pre><p>In this function, you can see the types of flags. You can set flags before and after “initialize” (pool initialization), “modifyPosition” (position update), “swap”, and “donate” to execute custom logic.</p><p>Note that “donate” is a function that does not exist in V3. This function is designed to increase the feeGrowthGlobal value by donating to the pool contract, so that all liquidity providers in the pool can benefit. This is how new fee structures can be built. In V4, there will be a myriad of pools, and by utilizing functions like “donate”, liquidity will naturally congregate in pools where liquidity providers can earn the most fees.</p><p>Returning to the code above, notice that only the flags for afterInitialize and afterSwap are set to true. And in the constructor function of the BaseHook contract, there is a function called validateHookAddress, as shown below.</p><p>v4-periphery/contracts/BaseHook.sol</p><pre>constructor(IPoolManager _poolManager) {<br>    poolManager = _poolManager;<br>    validateHookAddress(this);<br>}</pre><p>The BaseHook contract imports a library called Hooks, and the validateHookAddress function is implemented in the Hooks library.</p><p>v4-core/contracts/libraries/Hooks.sol</p><pre>uint256 internal constant BEFORE_INITIALIZE_FLAG = 1 &lt;&lt; 159;<br>uint256 internal constant AFTER_INITIALIZE_FLAG = 1 &lt;&lt; 158;<br>uint256 internal constant BEFORE_MODIFY_POSITION_FLAG = 1 &lt;&lt; 157;<br>uint256 internal constant AFTER_MODIFY_POSITION_FLAG = 1 &lt;&lt; 156;<br>uint256 internal constant BEFORE_SWAP_FLAG = 1 &lt;&lt; 155;<br>uint256 internal constant AFTER_SWAP_FLAG = 1 &lt;&lt; 154;<br>uint256 internal constant BEFORE_DONATE_FLAG = 1 &lt;&lt; 153;<br>uint256 internal constant AFTER_DONATE_FLAG = 1 &lt;&lt; 152;<br>...<br>function validateHookAddress(IHooks self, Calls memory calls) internal pure {<br>    if (<br>        calls.beforeInitialize != shouldCallBeforeInitialize(self)<br>            || calls.afterInitialize != shouldCallAfterInitialize(self)<br>            || calls.beforeModifyPosition != shouldCallBeforeModifyPosition(self)<br>            || calls.afterModifyPosition != shouldCallAfterModifyPosition(self)<br>            || calls.beforeSwap != shouldCallBeforeSwap(self) || calls.afterSwap != shouldCallAfterSwap(self)<br>            || calls.beforeDonate != shouldCallBeforeDonate(self) || calls.afterDonate != shouldCallAfterDonate(self)<br>    ) {<br>        revert HookAddressNotValid(address(self));<br>    }<br>}<br>...<br>function shouldCallBeforeInitialize(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_INITIALIZE_FLAG != 0;<br>}<br>function shouldCallAfterInitialize(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_INITIALIZE_FLAG != 0;<br>}<br>function shouldCallBeforeModifyPosition(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_MODIFY_POSITION_FLAG != 0;<br>}<br>function shouldCallAfterModifyPosition(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_MODIFY_POSITION_FLAG != 0;<br>}<br>function shouldCallBeforeSwap(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_SWAP_FLAG != 0;<br>}<br>function shouldCallAfterSwap(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_SWAP_FLAG != 0;<br>}<br>function shouldCallBeforeDonate(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_DONATE_FLAG != 0;<br>}<br>function shouldCallAfterDonate(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_DONATE_FLAG != 0;<br>}</pre><p>In the code above, the functions that start with shouldCall… are the ones that are used to check the hook flags each time, so you will see them often.</p><p>The first argument to the validateHookAddress function, “self”, is the address of the limit order contract, and the second argument, “calls”, is the result of the getHooksCalls function from above. The result of the getHookscalls function is compared to the result of the functions starting with shouldCall… and if there is a discrepancy, it is reverted.</p><p>If you look at the functions that start with shouldCall…, they all perform a “&amp;” operation on the hook contract address to check if a specific bit is set to 1. Since we only set the afterInitialize and afterSwap flags above, of the last 8 bits of the address, bits 1&lt;&lt;158 and 1&lt;&lt;154 should be set to 1, and the rest should be set to zero.</p><p>In other words, the most significant 8 bits of the address in binary should be set to 01000100. And if the address was represented in hexadecimal, it would be an address starting with 0x44…. Therefore, it should not be deployed to an arbitrary address, and the 8 bits should be set to the value of the hook flag via CREATE2.</p><p>The address can be precomputed in CREATE2 with the constructor address, the contract’s bytecode, the constructor argument values, and the salt value. Therefore, after the implementation is finished, you should fix the constructor address, bytecode, and constructor argument values, and brute force the salt value through the loop to create an address starting with 01000100. Just like Bitcoin’s PoW.</p><h3>Creating a pool</h3><p>The process of creating a pool is a big difference from V3. While V3 used the Factory pattern to deploy all pools as new contracts, V4 uses the Singleton pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XDqWQNY6hNIU97HJ.png" /><figcaption>V4 Singleton Pattern (Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p>The above image shows multiple paths to swap ETH to DAI. On the left, the transfer happens 6 times. However, if you look at the singleton pattern on the right, the transfers end with only 2 transfers. This saves a lot of gas. In the right side, each token pair is not managed by a contract, but by a state “pools”, a mapping variable in the v4-core/contracts/PoolManager contract. The key value is calculated as follows.</p><p>v4-core/contracts/types/PoolId.sol</p><pre>type PoolId is bytes32;<br>function toId(PoolKey memory poolKey) internal pure returns (PoolId) {<br>    return PoolId.wrap(keccak256(abi.encode(poolKey)));<br>}</pre><p>Encodes and hash the values of the PoolKey struct we covered above.</p><p>The following is a sequence diagram of the actions for creating a pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*mbZMbvi9G4JJz8NC.png" /><figcaption>Pool Creation, Sequence Diagram</figcaption></figure><p>I’d love to go through all the code line by line, but that would make this post too long, so I’ll leave out the parts that aren’t really relevant to the topic of this post, which is limit orders. Let’s look at the initialize function of the PoolManager contract.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function initialize(PoolKey memory key, uint160 sqrtPriceX96 ...<br>{<br>  ...<br>  tick = pools[id].initialize(sqrtPriceX96, protocolSwapFee, hookSwapFee, protocolWithdrawFee, hookWithdrawFee);<br><br>    if (key.hooks.shouldCallAfterInitialize()) {<br>        if (<br>            key.hooks.afterInitialize(msg.sender, key, sqrtPriceX96, tick)<br>                != IHooks.afterInitialize.selector<br>        ) { <br>            revert Hooks.InvalidHookResponse();<br>        }<br>    }<br><br>    emit Initialize(id, key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks);<br>}</pre><p>v4-core/contracts/libraries/Pool.sol</p><pre>function initialize(<br>    State storage self,<br>    uint160 sqrtPriceX96,<br>    uint8 protocolSwapFee,<br>    uint8 hookSwapFee,<br>    uint8 protocolWithdrawFee,<br>    uint8 hookWithdrawFee<br>) internal returns (int24 tick) {<br>    if (self.slot0.sqrtPriceX96 != 0) revert PoolAlreadyInitialized();<br>    tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);<br>    self.slot0 = Slot0({<br>        sqrtPriceX96: sqrtPriceX96,<br>        tick: tick,<br>        protocolSwapFee: protocolSwapFee,<br>        hookSwapFee: hookSwapFee,<br>        protocolWithdrawFee: protocolWithdrawFee,<br>        hookWithdrawFee: hookWithdrawFee<br>    });<br>}</pre><p>First, we can see the structure of Slot0 in the Pool.sol library and notice that the fields are different from V3 below.</p><p>v3-core/contracts/UniswapV3Pool.sol</p><pre>struct Slot0 {<br>        uint160 sqrtPriceX96;<br>        int24 tick;<br>        uint16 observationIndex;<br>        uint16 observationCardinality;<br>        uint16 observationCardinalityNext;<br>        uint8 feeProtocol;<br>        bool unlocked;<br>    }</pre><p>In V4, “observation”-related variables are gone, meaning price oracle functionality is not by default. In V3, even if no one was using oracles, updating oracle-related variables when a position needed to be updated was an unnecessary waste of gas. In V4, if you need oracle functionality, you can implement it as a hook and deploy the pool.</p><p>FeeProtocol in V3 is split into protocolSwapFee and protocolWithdrawFee in V4. Note that in V3, protocolFee was always 0 and could be changed by a governance vote. Also in V4, the variables hookSwapFee and hookWithdrawFee were added. These can be used to assign a fee to a swap or withdrawal, which is where hook developers can take some profit from.</p><p>The tick and sqrtPriceX96 are still there, but the variable “unlocked” is missing in V4. V4 uses lock, a callback pattern, and a value called delta, which we’ll cover in more detail later.</p><p>If you look at the initialize function of the poolManager contract in v4-core, after initializing the pool, it checks the flag through the shouldCallAfterInitialize function and calls the afterInitialize function of the hook contract.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function afterInitialize(address, PoolKey calldata key, uint160, int24 tick, bytes calldata)<br>    external<br>    override<br>    poolManagerOnly<br>    returns (bytes4)<br>{<br>    setTickLowerLast(key.toId(), getTickLower(tick, key.tickSpacing));<br>    return LimitOrder.afterInitialize.selector;<br>}</pre><p>“afterInitialize” function is really simple. Let’s say the tickSpacing is 60 and the current tick is 80, then a rounding operation is performed to store 60 as the value of tickLowerLast. The value of tickLowerLast is always updated when the tick changes after swap and is the value used when a limit order is filled.</p><p>Also, all hook functions always return a selector at the end, and the poolManager contract always checks that the response of the hook is the selector of the hook function.</p><h3>Placing a limit order</h3><p>The following is a sequence diagram of the “placing a limit order”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/0*OugI5yUePVwtbJRk.png" /><figcaption>Placing a limit order, sequence diagram</figcaption></figure><p>Before we get into the placing a limit order, let’s take a look at the limit order data structure.</p><pre>struct EpochInfo {<br>    bool filled;<br>    Currency currency0;<br>    Currency currency1;<br>    uint256 token0Total;<br>    uint256 token1Total;<br>    uint128 liquidityTotal;<br>    mapping(address =&gt; uint128) liquidity;<br>}<br><br>mapping(bytes32 =&gt; Epoch) public epochs;<br>mapping(Epoch =&gt; EpochInfo) public epochInfos;<br>...<br>function getEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne) public view returns (Epoch) {<br>    return epochs[keccak256(abi.encode(key, tickLower, zeroForOne))];<br>}</pre><p>Notice that the struct name uses the word “Epoch” instead of order or limitOrder. The word epoch is commonly used in blockchains to mean an interval or unit of time. In this case, it refers to each tick range that is spaced as far apart as the tickSpacing. It has multiple users placing limit orders in the same range, and it keeps the liquidity value of each user as a liquidity mapping variable inside the EpochInfo struct. And all the limit orders in the same range are processed at once.</p><p>The function to get the key value of epochInfo is “getEpoch”. “zeroForOne” is a boolean value that determines the direction, i.e. whether the position is long or short. And there can be multiple users’ limit orders with the same key.</p><p>Now let’s look at the “place” function, which places a limit order. We’ll cover the callback pattern and a value called delta while covering this function.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function place(PoolKey calldata key, int24 tickLower, bool zeroForOne, uint128 liquidity)<br>    external<br>    onlyValidPools(key.hooks)<br>{<br>    if (liquidity == 0) revert ZeroLiquidity();<br><br>    poolManager.lock(<br>        abi.encodeCall(this.lockAcquiredPlace, (key, tickLower, zeroForOne, int256(uint256(liquidity)), msg.sender))<br>    );<br>  ...<br>}<br>...<br>function lockAcquiredPlace(<br>    PoolKey calldata key,<br>    int24 tickLower,<br>    bool zeroForOne,<br>    int256 liquidityDelta,<br>    address owner<br>) external selfOnly {<br>    BalanceDelta delta = poolManager.modifyPosition(<br>        key,<br>        IPoolManager.ModifyPositionParams({<br>            tickLower: tickLower,<br>            tickUpper: tickLower + key.tickSpacing,<br>            liquidityDelta: liquidityDelta<br>        }),<br>        ZERO_BYTES<br>    );<br><br>    if (delta.amount0() &gt; 0) {<br>        if (delta.amount1() != 0) revert InRange();<br>        if (!zeroForOne) revert CrossedRange();<br>        // TODO use safeTransferFrom<br>        IERC20Minimal(Currency.unwrap(key.currency0)).transferFrom(<br>            owner, address(poolManager), uint256(uint128(delta.amount0()))<br>        );<br>        poolManager.settle(key.currency0);<br>    } else {<br>        if (delta.amount0() != 0) revert InRange();<br>        if (zeroForOne) revert CrossedRange();<br>        // TODO use safeTransferFrom<br>        IERC20Minimal(Currency.unwrap(key.currency1)).transferFrom(<br>            owner, address(poolManager), uint256(uint128(delta.amount1()))<br>        );<br>        poolManager.settle(key.currency1);<br>    }<br>}</pre><p>The “place” function calls the “lock” function of the poolManager contract, encoding the lockAcquiredPlace function and its argument values and passing them as arguments to the lock function.</p><p>Note that abi.encodeCall encodes a call to the function pointer. The result is the same as the commonly used encodeWithSelector, but the first parameter is a function pointer instead of a function selector.</p><p>There is a callback from PoolManager’s lock function to LimitOrder’s lockAcquired function. It then interacts with the poolManager contract through the “modifyPosition” and “settle” functions.</p><p>In V4, interacting with the PoolManager contract to change the state would have the following pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hhfx66indRh9c_4f.png" /><figcaption>Callback Pattern(Source: <a href="https://mirror.xyz/albertlin.eth/zE3lxVNZTxXwsLH0XpggUO_H_fmQMjmlEaFbMUaPYaA">Exploring the Core Mechanism of UniswapV4</a>)</figcaption></figure><p>So when the callback contract acquires the lock, ends its interaction with the poolManager, and leaves the lock, the value of delta must be zero. The value that the PoolManager owes the callback contract during the lock period, or that the callback contract owes the PoolManager, is called delta. This means that when they leave the lock, they must owe each other nothing for the transaction to succeed.<br>The functions that interact with the PoolManager are “swap”, “modifyPosition”, “donate”, “take”, “settle”, and “mint”.</p><p>In the lockAcquiredPlace function above, the modifyPosition function of the poolManager contract returns a value called delta. Note that unlike V3, in V4, modifyPosition is an external function, not a private function, and can be called directly from the callback contract (locker). What it does is update the position information and pay off what they owe each other.</p><p>The value returned by the poolManager, called delta, looks like this.</p><pre>function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        balanceDelta :=<br>            or(shl(128, _amount0), and(0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff, _amount1))<br>    }<br>}</pre><p>The delta is int256, where the left 128 bits represent amount0 and the right 128 bits represent amount1. And you can get the respective values with the functions amount0 and amount1.</p><pre>function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        _amount0 := shr(128, balanceDelta)<br>    }<br>}<br><br>function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        _amount1 := balanceDelta<br>    }<br>}</pre><p>“amount0” and “amount1” are the respective amounts of a pair of tokens. If the value is positive, the callback contract owes the PoolManager, and if it is negative, the PoolManager owes the callback contract.</p><p>The lockAcquiredPlace function in LimitOrder.sol checks to see if amount0 or amount1 is positive, and if it is, it transfers the corresponding token to the PoolManager and calls the “settle” function. The “modifyPosition”, “transfer”, and “settle” functions make the delta value of the PoolManager go from zero to zero. Now let’s see how the delta value is handled inside the poolManager.</p><p>v4-core/contracts/PoolManager.sol</p><pre>/// @inheritdoc IPoolManager<br>function lock(bytes calldata data) external override returns (bytes memory result) {<br>    lockData.push(msg.sender);<br><br>    // the caller does everything in this callback, including paying what they owe via calls to settle<br>    result = ILockCallback(msg.sender).lockAcquired(data);<br>    if (lockData.length == 1) {<br>        if (lockData.nonzeroDeltaCount != 0) revert CurrencyNotSettled();<br>        delete lockData;<br>    } else {<br>        lockData.pop();<br>    }<br>}<br>...<br>function _accountDelta(Currency currency, int128 delta) internal {<br>    if (delta == 0) return;<br><br>    address locker = lockData.getActiveLock();<br>    int256 current = currencyDelta[locker][currency];<br>    int256 next = current + delta;<br><br>    unchecked {<br>        if (next == 0) {<br>            lockData.nonzeroDeltaCount--;<br>        } else if (current == 0) {<br>            lockData.nonzeroDeltaCount++;<br>        }<br>    }<br><br>    currencyDelta[locker][currency] = next;<br>}</pre><p>The lock function pushes the callback contract address in the lockData variable.</p><p>Then, the _accountDelta function updates the currencyDelta variable with the callback contract address and the token address as the key value through a function such as “modifyPosition” or “swap” to update the value of how much is owed. If that value is non-zero, it increments a variable called nonzeroDeltaCount. If next is calculated to be zero, meaning that the value owed has been paid, it decrements the nonzeroDeltaCount variable.</p><p>In the lock function, the callback contract’s lockAcquired function ends and at the end of the lock function, if the nonzeroDeltaCount of lockData is non-zero, it is reverted; if it is zero, the lock function succeeds and the transaction succeeds.</p><p>Back to the lockAcquiredPlace function of the limit order, let’s summarize the process of changing the delta value by interacting with the PoolManager three times: modifyPosition → transferFrom → settle.</p><p>(1) modifyPosition</p><p>In a limit order, “modifyPosition” is a function that chooses between currency0 and currency1 and provides liquidity to one side. Let’s assume we want to provide liquidity in currency0.<br>currency[&lt;limitOrderAddress&gt;][&lt;currency0Address&gt;] = +x (positive)<br>nonzeroDeltaCount will be 1.</p><p>(2) transferFrom</p><p>transfer currency0 an amount of x to the poolManager contract</p><p>(3) settle</p><pre>function settle(Currency currency) external payable override noDelegateCall onlyByLocker returns (uint256 paid) {<br>        uint256 reservesBefore = reservesOf[currency];<br>        reservesOf[currency] = currency.balanceOfSelf();<br>        paid = reservesOf[currency] - reservesBefore;<br>        // subtraction must be safe<br>        _accountDelta(currency, -(paid.toInt128()));<br>    }</pre><ul><li>Here, it retrieves the last saved value through reservesOf[&lt;currency0Address&gt;] and updates it by retrieving the current poolManager’s currency0 balance value.</li><li>It compares the last saved value with the current updated value and makes the difference, x, negative and passes it as an argument to the _accountDelta function.</li><li>The result is currency[][] = +x -x = 0 and nonzeroDeltaCount is zero, allowing it to break out of the lock.</li></ul><p>The modifyPosition function is not much different from V3 except that it calculates delta and returns delta, and it takes into account different fee policies. The logic for updating accumulated fees and initializing ticks using tickBitmap is the same.</p><p>Additionally, lockData related functions are implemented in v4-core/contracts/libraries/LockDataLibrary.sol.</p><pre>library LockDataLibrary {<br>uint256 private constant OFFSET = uint256(keccak256(&quot;LockData&quot;));<br><br>/// @dev Pushes a locker onto the end of the queue, and updates the sentinel storage slot.<br>function push(IPoolManager.LockData storage self, address locker) internal {<br>    // read current value from the sentinel storage slot<br>    uint128 length = self.length;<br>    unchecked {<br>        uint256 indexToWrite = OFFSET + length; // not in assembly because OFFSET is in the library scope<br>        /// @solidity memory-safe-assembly<br>        assembly {<br>            // in the next storage slot, write the locker<br>            sstore(indexToWrite, locker)<br>        }<br>        // update the sentinel storage slot<br>        self.length = length + 1;<br>    }<br>}<br>...</pre><p>This library implements custom storage for “Queue”. It implements push and pop functions just like a queue. It stores the address of the locker starting at slot uint256(keccak256(“LockData”)). For reference, the value of uint256(keccak256(“LockData”)) is 53391651520919458808831464411208423921832704174599079787929421271630035089670.</p><p>And if you look at v4-core/contracts/libraries/Pool.sol, the TickInfo struct is as follows.</p><pre>struct TickInfo {<br> uint128 liquidityGross;<br> int128 liquidityNet;<br> // fee growth per uint of liquidity on the _other_ side of this tick (relative to the current tick) only has relative meaning, not absolute - the value depends on when the tick is initialized<br> uint256 feeGrowthOutside0x128;<br> uint256 feeGrowthOutside1x128;<br>}</pre><p>Here, liquidityGross and liquidityNet together are 256 bits, so they take up one slot. Then, we use the shift operation in the assembly block to fetch and update each value.</p><p>You can see the updateTick function in v4-core/contracts/libraries/Pool.sol.</p><pre>function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper)<br>    internal<br>    returns (bool flipped, uint128 liquidityGrossAfter)<br>{<br>    TickInfo storage info = self.ticks[tick];<br><br>    uint128 liquidityGrossBefore;<br>    int128 liquidityNetBefore;<br>    assembly {<br>        // load first slot of info which contains liquidityGross and liquidityNet packed<br>        // where the top 128 bits are liquidityNet and the bottom 128 bits are liquidityGross<br>        let liquidity := sload(info.slot)<br>        // slice off top 128 bits of liquidity (liquidityNet) to get just liquidityGross<br>        liquidityGrossBefore := shr(128, shl(128, liquidity))<br>        // shift right 128 bits to get just liquidityNet<br>        liquidityNetBefore := shr(128, liquidity)<br>    }<br>    liquidityGrossAfter = liquidityDelta &lt; 0<br>        ? liquidityGrossBefore - uint128(-liquidityDelta)<br>        : liquidityGrossBefore + uint128(liquidityDelta);<br><br>    flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);<br><br>    if (liquidityGrossBefore == 0) {<br>        // by convention, we assume that all growth before a tick was initialized happened _below_ the tick<br>        if (tick &lt;= self.slot0.tick) {<br>            info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128;<br>            info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128;<br>        }<br>    }<br>    // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)<br>    int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta;<br>    assembly {<br>        // liquidityGrossAfter and liquidityNet are packed in the first slot of `info`<br>        // So we can store them with a single sstore by packing them ourselves first<br>        sstore(<br>            info.slot,<br>            // bitwise OR to pack liquidityGrossAfter and liquidityNet<br>            or(<br>                // liquidityGross is in the low bits, upper bits are already 0<br>                liquidityGrossAfter,<br>                // shift liquidityNet to take the upper bits and lower bits get filled with 0<br>                shl(128, liquidityNet)<br>            )<br>        )<br>    }<br>}</pre><p>This reduces storage operations and saves gas. liquidityGross and liquidityNet are the same values used in V3.</p><p><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-2-c130997a4481">In the next post</a>, I’ll cover processing and withdrawing limit orders, as well as EIP-1153 and testing hook contracts in the Foundry environment.</p><p>Thanks for reading.</p><p>References</p><ul><li>Uniswap V4 Whitepaper (<a href="https://github.com/Uniswap/v4-core/blob/main/docs/whitepaper-v4.pdf">https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf</a>)</li><li>v4-core (<a href="https://github.com/Uniswap/v4-core">https://github.com/Uniswap/v4-core</a>)</li><li>v4-periphery (<a href="https://github.com/Uniswap/v3-periphery">https://github.com/Uniswap/v3-periphery</a>)</li><li>Uniswap Blog (<a href="https://blog.uniswap.org/uniswap-v4">https://blog.uniswap.org/uniswap-v4</a>)</li></ul><p>Thanks to Aaron, Kevin, Zena for feedback on this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586233620584" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokamak-network/uniswap-v4-limit-order-hook-part-1-586233620584">Uniswap V4 Limit Order Hook part 1</a> was originally published in <a href="https://medium.com/tokamak-network">Tokamak Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap V4 지정가 주문 훅 part 2]]></title>
            <link>https://medium.com/tokamak-network/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%EB%B6%84%EC%84%9D-%EC%8B%9C%EB%A6%AC%EC%A6%88-part-2-6d46e01108a6?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d46e01108a6</guid>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[onther]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[tokamak-network]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 05:06:42 GMT</pubDate>
            <atom:updated>2023-11-21T07:37:33.859Z</atom:updated>
            <content:encoded><![CDATA[<h4>스마트 컨트랙트 소스코드 레벨 분석</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*tWB0-T59IenziuUk.png" /><figcaption>유니스왑 V4 로고(Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%ED%9B%85-part-1-1075a8c9e654">첫 번째 포스팅</a>에서 V3에서의 지정가 주문, V4 컨트랙트 구성도, V4 훅 플로우, 훅 컨트랙트 설정 및 CREATE2배포, 풀 생성 그리고 지정가 주문 넣기에 대해서 다뤘다.</p><p>이어서 지정가 주문을 처리하고 withdraw, 그리고 아직 다루지 않은 부분들을 이번 포스팅에서 다루겠다.</p><p>*V3에 대한 이해도가 어느 정도 있어야 읽기 편하다.</p><p>영문 버전은 아래 링크에서 확인하실 수 있습니다:</p><ul><li><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">Uniswap V4 Limit Order Hook part 1</a></li><li><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-2-c130997a4481">Uniswap V4 Limit Order Hook part 2</a></li></ul><p>목차는 다음과 같다.</p><ul><li>Swap &amp; After Swap</li><li>Withdraw</li><li>Foundry 환경에서의 훅 컨트랙트 테스트 셋업</li><li>지정가 주문 테스트</li><li>EIP-1153 : Transient Storage</li></ul><h3>Swap &amp; After Swap</h3><p>다음은 Swap &amp; AfterSwap 동작에 대한 시퀀스 다이어그램이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBU8MeNoWvRFlfNhbHZiBA.png" /><figcaption>Swap &amp; After Swap, 시퀀스 다이어그램</figcaption></figure><p>이제 swap을 통해서 tick이 바뀌고, afterSwap 훅을 통해서 지정가 주문을 처리하는 부분을 다룰 것이다.</p><p>먼저 swap은 swap 전후에 훅 flag를 검사하는 것 외에 v3와 크게 달라진 부분이 없이 slot0을 업데이트 시켜준다. 물론 lock을 획득하고 delta 값을 0으로 만들어 주고 lock에서 벗어나게 된다.</p><p>v4-core/contracts/test/PoolSwapTest.sol에서 lockAcquired 함수를 볼 수 있다.</p><pre>function lockAcquired(bytes calldata rawData) external returns (bytes memory) {<br>    require(msg.sender == address(manager));<br>    CallbackData memory data = abi.decode(rawData, (CallbackData));<br><br>    BalanceDelta delta = manager.swap(data.key, data.params, new bytes(0));<br>  if (data.params.zeroForOne) {<br>        if (delta.amount0() &gt; 0) {<br>            if (data.testSettings.settleUsingTransfer) {<br>                if (data.key.currency0.isNative()) {<br>                    manager.settle{value: uint128(delta.amount0())}(data.key.currency0);<br>                } else {<br>                    IERC20Minimal(Currency.unwrap(data.key.currency0)).transferFrom(<br>                        data.sender, address(manager), uint128(delta.amount0())<br>                    );<br>                    manager.settle(data.key.currency0);<br>                }<br>            } else {<br>                // the received hook on this transfer will burn the tokens<br>                manager.safeTransferFrom(<br>                    data.sender,<br>                    address(manager),<br>                    uint256(uint160(Currency.unwrap(data.key.currency0))),<br>                    uint128(delta.amount0()),<br>                    &quot;&quot;<br>                );<br>            }<br>        }<br>        if (delta.amount1() &lt; 0) {<br>            if (data.testSettings.withdrawTokens) {<br>                manager.take(data.key.currency1, data.sender, uint128(-delta.amount1()));<br>            } else {<br>                manager.mint(data.key.currency1, data.sender, uint128(-delta.amount1()));<br>            }<br>        }<br>    } else {<br>       ...생략<br>}</pre><p>poolManager의 swap 함수 역시 delta를 반환해 준다. 그리고 tokenIn의 델타 값은 poolManager 컨트랙트에서 양수가 될 것이고, 유동성을 제공할 때처럼 transferFrom과 settle을 통해서 delta 값을 0으로 만들어준다. tokenOut의 경우 델타값이 poolManager 컨트랙트에서 음수이고, take라는 함수를 통해서 delta 값을 0으로 만들어주게 된다.</p><p>transferFrom과 settle은 유동성을 제공할 때 다뤘으므로, take 함수를 한번 보겠다.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function take(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>    _accountDelta(currency, amount.toInt128());<br>    reservesOf[currency] -= amount;<br>    currency.transfer(to, amount);<br>}</pre><p>매우 간단하다. _accountDelta 함수를 통해서 델타값에 amount만큼을 더해 음수에서 0으로 만들어주고, reservesOf 변수를 업데이트해 주고 transfer 해준다.</p><p>그리고 PoolManager 컨트랙트의 swap 함수에는 다음과 같이 afterSwap flag를 체크하고 limitOrder 컨트랙트의 afterSwap 함수를 실행하게 된다.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function swap(<br>    PoolKey memory key,<br>    IPoolManager.SwapParams memory params,<br>    bytes calldata hookData<br>) external override noDelegateCall onlyByLocker returns<br> ...<br> if (key.hooks.shouldCallAfterSwap()) {<br>      if (key.hooks.afterSwap(msg.sender, key, params, delta, hookData) != IHooks.afterSwap.selector) {<br>          revert Hooks.InvalidHookResponse();<br>      }<br>  }</pre><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function afterSwap(<br>    address,<br>    PoolKey calldata key,<br>    IPoolManager.SwapParams calldata params,<br>    BalanceDelta,<br>    bytes calldata<br>) external override poolManagerOnly returns (bytes4) {<br>    (int24 tickLower, int24 lower, int24 upper) = _getCrossedTicks(key.toId(), key.tickSpacing);<br>    if (lower &gt; upper) return LimitOrder.afterSwap.selector;<br><br>    // note that a zeroForOne swap means that the pool is actually gaining token0, so limit<br>    // order fills are the opposite of swap fills, hence the inversion below<br>    bool zeroForOne = !params.zeroForOne;<br>    for (; lower &lt;= upper; lower += key.tickSpacing) {<br>        _fillEpoch(key, lower, zeroForOne);<br>    }<br><br>    setTickLowerLast(key.toId(), tickLower);<br>    return LimitOrder.afterSwap.selector;<br>}</pre><p>먼저 poolManagerOnly 모디파이어를 통해서, msg.sender가 poolManager 인지 검사한다.</p><p>afterSwap 함수를 보면, 이렇게 swap을 하는 사용자가 for 문을 돌면서 _fillEpoch 함수를 통해서 모든 지정가 주문을 처리하고 있다. for 문에서는 tickLowerLast에서부터, swap을 통해서 바뀐 새로운 tick까지 tickSpacing 만큼 더해가면서 for 문을 돌고 있다. 그만큼 swap 할 때 가스비가 더 든다는 것이다.</p><p>*초반에 tickSpacing과 fee 티어를 자유롭게 세팅할 수 있다고 언급했었다. tickSpacing을 어느 정도 큰 값으로 하면 for 문을 적게 돌 수 있으나, 지정가 주문의 tick 범위가 넓어져 UX가 안 좋아질 수 있다. fee를 낮게 책정한다면 그만큼 order router나 <a href="https://blog.uniswap.org/how-uniswapv4-uniswapx-work-together">유니스왑X</a>에서 이 풀이 경로에 잡혀 지정가 주문들이 빨리 처리될 수 있고, 높게 책정한다면 지정가 주문이 처리되는 유저들은 fee를 더해서 받으므로 결국 더 좋은 가격에 채결될 수 있다. 여러 가지 사항들을 고려해서 적당한 tickSpacing과 fee를 책정하는 것이 중요할 것이다.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol의 _fillEpoch함수를 보자.</p><pre>function _fillEpoch(PoolKey calldata key, int24 lower, bool zeroForOne) internal {<br>    Epoch epoch = getEpoch(key, lower, zeroForOne);<br>    if (!epoch.equals(EPOCH_DEFAULT)) {<br>        EpochInfo storage epochInfo = epochInfos[epoch];<br><br>        epochInfo.filled = true;<br><br>        (uint256 amount0, uint256 amount1) = abi.decode(<br>            poolManager.lock(<br>                abi.encodeCall(this.lockAcquiredFill, (key, lower, -int256(uint256(epochInfo.liquidityTotal))))<br>            ),<br>            (uint256, uint256)<br>        );<br>        unchecked {<br>            epochInfo.token0Total += amount0;<br>            epochInfo.token1Total += amount1;<br>        }<br>        setEpoch(key, lower, zeroForOne, EPOCH_DEFAULT);<br>        emit Fill(epoch, key, lower, zeroForOne);<br>    }<br>}</pre><p>위 함수를 보면 poolManager와 상호작용하기 위해 lock 함수에 encoding 한 lockAcquiredFill 함수를 인자로 넘기면서 호출하고 있다. 그럼 lockAcquiredFill 함수를 보자.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function lockAcquiredFill(PoolKey calldata key, int24 tickLower, int256 liquidityDelta)<br>    external<br>    selfOnly<br>    returns (uint128 amount0, uint128 amount1)<br>{<br>    BalanceDelta delta = poolManager.modifyPosition(<br>        key,<br>        IPoolManager.ModifyPositionParams({<br>            tickLower: tickLower,<br>            tickUpper: tickLower + key.tickSpacing,<br>            liquidityDelta: liquidityDelta<br>        }),<br>        ZERO_BYTES<br>    );<br>    if (delta.amount0() &lt; 0) poolManager.mint(key.currency0, address(this), amount0 = uint128(-delta.amount0()));<br>    if (delta.amount1() &lt; 0) poolManager.mint(key.currency1, address(this), amount1 = uint128(-delta.amount1()));<br>}</pre><p>lockAcquiredFill 함수는 지정가 주문을 처리하는 함수이므로, 유저들이 넣은 유동성들을 풀에서 제거하게 된다. 이는 전편에서 다뤘던 “V3에서의 지정가 주문”의 decreaseLiquidity 함수와 유사하다. 즉 withdraw는 하지 않고 modifyPosition을 하게 된다.</p><p>그럼 poolManager 컨트랙트에서 유동성을 제거하는 token의 델타값은 음수가 되어있을 것이다. 이제 take 함수를 통해서 token을 돌려받고 델타값을 0으로 만들어주면 될까? 여기서는 그렇고 있지 않다. 즉 전편에서 다뤘던 “V3에서의 지정가 주문”의 collect를 수행하지 않는 것이다.</p><p>어떻게 lock에서 벗어날까? V4에서는 V3에서는 없었던 ERC1155를 활용한다. 아래 if 문을 보면 delta 값이 음수 면 자기 자신인 limitOrder 컨트랙트 주소에 해당 amount 만큼 ERC1155토큰을 민트 하게 된다.</p><p>v4-core/contracts/PoolManager.sol의 mint 함수를 보자.</p><pre>/// @inheritdoc IPoolManager<br>function mint(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>    _accountDelta(currency, amount.toInt128());<br>    _mint(to, currency.toId(), amount, &#39;&#39;);<br>}</pre><p>이렇게 _accountDelta 함수를 통해서 amount만큼을 델타값에 더해서 델타를 0으로 만든다. 그리고 ERC1155를 mint 해주고 있다. ERC1155는 위와 같이 토큰 주소를 id 값으로 하여 같은 토큰을 여러 개 mint 할 수 있다. ERC721과는 다르게, 같은 id를 갖는 ERC1155 토큰끼리는 fungible 하다는 특성을 가지고 있다.</p><p>이렇게 토큰의 transfer 없이, poolManager가 훅 컨트랙트나 유저에게 빚진 값을 훅 컨트랙트나 유저가 바로 take 하지 않아도, ERC1155 토큰을 민트 하여 가지고 있음으로써 나중에 withdraw 할 수 있도록 보장을 받는 것이다. 토큰의 transfer 없이 poolManager와 유저 간 회계를 처리할 수 있다고 해서 ERC1155 Accounting이라고 유니스왑 V4 백서에도 명시되어 있다.</p><p>그리고 v4-periphery/contracts/hooks/examples/LimitOrder.sol에는 onERC1155Received 함수가 구현되어 있다.</p><pre>function onERC1155Received(address, address, uint256, uint256, bytes calldata) external view returns (bytes4) {<br>    if (msg.sender != address(poolManager)) revert NotPoolManagerToken();<br>    return IERC1155Receiver.onERC1155Received.selector;<br>}</pre><p>이렇게 EOA가 아닌 Contract는 ERC1155 토큰을 받기 위해서 onERC1155Received를 필수적으로 구현하고 있어야 한다. 표준에 의해서, onERC1155Received를 구현하지 않은 컨트랙트는 ERCC1155 토큰을 받을 수 없다.</p><p>그리고 위의 onERC1155Received 함수를 보면 msg.sender가 poolManager 인지 체크하는 과정을 통해서 악의적으로 ERC1155토큰을 다른 곳에서 구해서 poolManager의 토큰을 withdraw 할 수 없게 막고 있다.</p><h3>Withdraw</h3><p>다음은 Withdraw 동작에 대한 시퀀스 다이어그램이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*IWJzdOI3Q15Ios3G34PnMA.png" /><figcaption>Withdraw, 시퀀스 다이어그램</figcaption></figure><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol의 withdraw 함수를 보자.</p><pre>function withdraw(Epoch epoch, address to) external returns (uint256 amount0, uint256 amount1) {<br>    EpochInfo storage epochInfo = epochInfos[epoch];<br>    if (!epochInfo.filled) revert NotFilled();<br><br>    uint128 liquidity = epochInfo.liquidity[msg.sender];<br>    if (liquidity == 0) revert ZeroLiquidity();<br>    delete epochInfo.liquidity[msg.sender];<br><br>    uint256 token0Total = epochInfo.token0Total;<br>    uint256 token1Total = epochInfo.token1Total;<br>    uint128 liquidityTotal = epochInfo.liquidityTotal;<br><br>    amount0 = FullMath.mulDiv(token0Total, liquidity, liquidityTotal);<br>    amount1 = FullMath.mulDiv(token1Total, liquidity, liquidityTotal);<br><br>    epochInfo.token0Total = token0Total - amount0;<br>    epochInfo.token1Total = token1Total - amount1;<br>    epochInfo.liquidityTotal = liquidityTotal - liquidity;<br>    poolManager.lock(<br>        abi.encodeCall(this.lockAcquiredWithdraw, (epochInfo.currency0, epochInfo.currency1, amount0, amount1, to))<br>    );<br><br>    emit Withdraw(msg.sender, epoch, liquidity);<br>}</pre><p>위 함수를 보면 withdraw 하는 유저의 liquidity 값을 불러오고, 해당 liquidity를 liquidityTotal로 나누고 tokenTotal을 곱해서 비율에 맞는 만큼을 withdraw 하게 된다. 그리고 epochInfo 변수를 업데이트해 준다.</p><p>어느 때와 마찬가지로, poolManager 컨트랙트의 lock 함수를 호출하고, lockAcquiredWithdraw 함수를 통해서 poolManager 컨트랙트와 상호작용하게 된다.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol의 lockAcquiredWithdraw 함수를 보자.</p><pre>function lockAcquiredWithdraw(<br>    Currency currency0,<br>    Currency currency1,<br>    uint256 token0Amount,<br>    uint256 token1Amount,<br>    address to<br>) external selfOnly {<br>    if (token0Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency0))), token0Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency0, to, token0Amount);<br>    }<br>    if (token1Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency1))), token1Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency1, to, token1Amount);<br>    }<br>}</pre><p>여기서 withdraw할 tokenAmount 만큼의 ERC1155토큰을 poolManager 컨트랙트에게 transfer 하고 take 함수를 호출한다.</p><p>swap에서 take 함수를 다뤘으니 기억할 것이다. poolManager에서 해당 token의 델타값을 음수로 만들어줘야 take 함수를 호출하여 withdraw 할 수 있다. ERC1155토큰을 poolManager 컨트랙트에게 transfer 하는 과정에서 해당 token의 델타값을 음수로 만들 수 있다. PoolManager도 컨트랙트이기 때문에 onERC1155Received를 구현해놨다. 해당 함수를 보자.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function onERC1155Received(address, address, uint256 id, uint256 value, bytes calldata) external returns (bytes4) {<br>    if (msg.sender != address(this)) revert NotPoolManagerToken();<br>    _burnAndAccount(CurrencyLibrary.fromId(id), value);<br>    return IERC1155Receiver.onERC1155Received.selector;<br>}<br><br>function _burnAndAccount(Currency currency, uint256 amount) internal {<br>    _burn(address(this), currency.toId(), amount);<br>    _accountDelta(currency, -(amount.toInt128()));<br>}</pre><p>PoolManager는 받은 ERC1155를 burn 시키고, _accountDelta 함수를 통해서 해당 토큰의 델타값을 음수로 만들고 nonzeroDeltaCount 1을 증가시킨다. 그리고 swap에서 다뤘던 take 함수를 통해서 withdraw 하고, 델타값과 nonzeroDeltaCount을 0으로 만들어줌으로써 lock에서 벗어나게 된다.</p><p>이렇게 UniswapV4의 전반적인 것을 분석했고 특히 지정가 주문에 대해서 다뤄봤다. 이제 실 데이터를 기반으로 테스트를 진행한다.</p><h3>Foundry 환경에서의 훅 컨트랙트 테스트 셋업</h3><p>먼저 유니스왑 V4 코드는 파운드리 프레임워크 환경에서 개발되었으며 테스트 코드 예시가 공개되어 있다. 먼저 훅 컨트랙트를 개발하기 위해 개발 환경을 셋팅하는 것을 다루겠다. 시작하기 전에 파운드리를 먼저 다운로드 받아야 한다. 다운로드는 이 <a href="https://book.getfoundry.sh/getting-started/installation">Foundry Docs</a> 가이드를 따라서 진행하면 된다.</p><p>그리고 디렉토리를 만들고 다음 명령어를 통해서 파운드리 환경을 세팅해 준다.</p><pre>forge init .</pre><p>만약에 다음과 같은 에러가 난다면…</p><pre>Error: <br>Cannot run `init` on a non-empty directory.</pre><p>명령어 뒤에 — force를 붙여주자.</p><p>명령어 실행 후 폴더와 파일들을 살펴보면, src 폴더에 Counter.sol 파일과 test 폴더의 간단한 테스트 코드를 확인할 수 있다. 그리고 forge-std라는 라이브러리가 함께 다운로드 된다.</p><p>BaseHook 컨트랙트가 있는 v4-periphery 패키지를 다운로드하겠다.</p><pre>forge install https://github.com/Uniswap/periphery-next</pre><p>이 명령어는 v4-periphery의 깃허브 레포지토리를 lib 폴더로 클론 한다. 그리고 해당 컨트랙트를 가져다 쓰면 된다. 파운드리 환경에서는 컨트랙트 파일을 node_modules가 아닌 lib 폴더에서 import를 한다. BaseHook 컨트랙트를 import 해보자.</p><pre>import {BaseHook} from &quot;../lib/periphery-next/contracts/BaseHook.sol&quot;;</pre><p>앞에 붙은 ../lib 와 /contracts를 생략하기 위해서 파운드리 환경에서는 remappings라는 것을 세팅해 준다. 다음 명령어를 실행해 보자.</p><pre>forge remappings</pre><p>결과</p><pre>@ensdomains/=lib/periphery-next/lib/v4-core/node_modules/@ensdomains/<br>@openzeppelin/=lib/periphery-next/lib/openzeppelin-contracts/<br>@uniswap/v4-core/=lib/periphery-next/lib/v4-core/<br>ds-test/=lib/forge-std/lib/ds-test/src/<br>erc4626-tests/=lib/periphery-next/lib/openzeppelin-contracts/lib/erc4626-tests/<br>forge-gas-snapshot/=lib/periphery-next/lib/forge-gas-snapshot/src/<br>forge-std/=lib/forge-std/src/<br>hardhat/=lib/periphery-next/lib/v4-core/node_modules/hardhat/<br>openzeppelin-contracts/=lib/periphery-next/lib/openzeppelin-contracts/<br>openzeppelin/=lib/periphery-next/lib/openzeppelin-contracts/contracts/<br>periphery-next/=lib/periphery-next/contracts/<br>solmate/=lib/periphery-next/lib/solmate/src/<br>v4-core/=lib/periphery-next/lib/v4-core/contracts/</pre><p>이렇게 파운드리는 lib 폴더를 참고해서 자동으로 remappings 들을 출력해 준다. 마지막에서 3번째 줄이 periphery-next는 lib/periphery-next/contracts와 같다는 내용이다. 루트 폴더에 remappings.txt 파일을 생성하고 콘솔 결과 내용을 붙여 넣는다. 그럼 다음과 같이 import 문을 수정할 수 있다.</p><pre>import {BaseHook} from &quot;periphery-next/BaseHook.sol&quot;;</pre><p>이 환경에서 훅 컨트랙트를 개발하고, 테스트 코드를 작성하여 테스트해 볼 수 있다. 지정가 주문 훅 컨트랙트는 v4-periphery/hooks/examples/LimitOrder.sol을 참고하고 테스트 코드는 v4-periphery/test/LimitOrder.t.sol을 참고하면 된다.</p><p>Mocha 테스트 환경에서의 beforeEach가 파운드리에서는 setUp이다. setUp 함수는 각 테스트 케이스가 실행되기 전에 호출되는 함수다. setUp 코드는 다음과 같다.</p><pre>function setUp() public {<br>    initializeTokens();<br>    token0 = TestERC20(Currency.unwrap(currency0));<br>    token1 = TestERC20(Currency.unwrap(currency1));<br>    manager = new PoolManager(500000);<br>    ...<br>}</pre><p>먼저 PoolManager 컨트랙트를 생성할 때, 500000을 인자로 넘겨준다. 해당 값은 PoolManager가 상속하고 있는 Fees.sol의 controllerGasLimit라는 변수에 할당되어 초기화된다. controllerGasLimit은 Fees.sol의 _fetchPorotoclFees 함수에서 사용된다.</p><p>v4-core/contracts/Fees.sol</p><pre>function _fetchProtocolFees(<br>    PoolKey memory key<br>) internal view returns (uint8 protocolSwapFee, uint8 protocolWithdrawFee) {<br>    if (address(protocolFeeController) != address(0)) {<br>        // note that EIP-150 mandates that calls requesting more than 63/64ths of remaining gas<br>        // will be allotted no more than this amount, so controllerGasLimit must be set with this<br>        // in mind.<br>        if (gasleft() &lt; controllerGasLimit) revert ProtocolFeeCannotBeFetched();<br>        try protocolFeeController.protocolFeesForPool{gas: controllerGasLimit}(key) returns (<br>            uint8 updatedProtocolSwapFee,<br>            uint8 updatedProtocolWithdrawFee<br>        ) {<br>            protocolSwapFee = updatedProtocolSwapFee;<br>            protocolWithdrawFee = updatedProtocolWithdrawFee;<br>        } catch {<br>            console.log(&#39;what!?&#39;);<br>        }<br><br>        _checkProtocolFee(protocolSwapFee);<br>        _checkProtocolFee(protocolWithdrawFee);<br>    }<br>}</pre><p>먼저 protocolFeeController가 세팅되어 있는지를 체크한다. 오직 owner만 protocolFeeController를 어떤 주소로 세팅할 수 있으며, 거버넌스 투표를 통해서 정해질 것이다. 그리고 protocolSwapFee와 protocolWithdrawFee를 반환해 주는 protocolFeeController의 protocolFeesForPool 함수를 호출할 때, 가스를 controllerGasLimit으로 명시하여 그만큼 이상의 gas를 그 함수에서 못쓰게 만들고 있다.</p><p>EIP-150에 의해서 잔여 가스(gasLeft())의 63/64를 초과하여 할당하지 않도록 되어 있으므로, 이를 염두에 두고 controllerGasLimit을 설정해야 한다. 솔리디티 공식 문서에서 opcode의 가스 비용은 향후 변경될 수 있으므로 가스 값을 명시적으로 지정하는 것은 권장하고 있지 않지만, 이렇게 구현되어 있고 심지어 controllerGasLimit을 바꿀 수 있는 onlyOwner 함수도 찾아볼 수 없다. 만약에 opcode의 가스 비용이 향후 변경되어 더 이상 protocolFeeController의 protocolFeesForPool 함수를 호출할 수 없다면, protocolFeeController를 새로 세팅해 줘야 할 것이다.</p><p>v4-core/contracts/test/ProtocolFeeControllerTest.sol에서 protocolFeesForPool 함수 예시를 찾아볼 수 있다.</p><pre>function protocolFeesForPool(PoolKey memory key) external view returns (uint8, uint8) {<br>    return (swapFeeForPool[key.toId()], withdrawFeeForPool[key.toId()]);<br>}</pre><p>이 함수는 가스가 500000이면 충분해 보이며, 현재 v4-periphery에서 모든 테스트 코드 예제에서 controllerGasLimit을 500000으로 세팅하고 있으므로, 이 값을 사용하겠다.</p><p>_fetchPorotoclFees 함수는 PoolManager 컨트랙트의 initialize 함수와 setProtocolFees 함수에서 사용된다. Protocol fee가 정해지기 전에 initialize된 pool들은 setProtocolFees 함수를 통해서 protocol fee를 세팅해 줄 수 있다.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function setProtocolFees(PoolKey memory key) external {<br>    (uint8 newProtocolSwapFee, uint8 newProtocolWithdrawFee) = _fetchProtocolFees(key);<br>    PoolId id = key.toId();<br>    pools[id].setProtocolFees(newProtocolSwapFee, newProtocolWithdrawFee);<br>    emit ProtocolFeeUpdated(id, newProtocolSwapFee, newProtocolWithdrawFee);<br>}</pre><p>Pool들의 개수가 워낙 많아질 것이다 보니, 이렇게 아무나 가스비를 희생해서 실행할 수 있게끔 만들어 놨다.</p><p>setUp 함수를 이어서 완성해나가겠다.</p><p>전 편의 “훅 컨트랙트 설정 및 CREATE2 배포”에서 CREATE2를 사용하여 훅 컨트랙트의 앞 8비트를 특정 비트로 설정해야 훅 컨트랙트를 배포할 수 있다고 언급했다. 이렇게 하지 않고 Foundry 환경에서 테스트할 수 있는 방법이 있다.</p><p>먼저 LimitOrder 컨트랙트는 afterInitialize와 afterSwap의 true flag를 가진다.</p><p>AFTER_INITIALIZE_FLAG</p><p>⇒ 1 &lt;&lt; 158 ⇒ 2¹⁵⁸</p><p>⇒ to hex ⇒ 4000000000000000000000000000000000000000 (0 39개)</p><p>AFTER_SWAP_FLAG</p><p>⇒ 1&lt;&lt;154 ⇒ 2¹⁵⁴</p><p>⇒ to hex ⇒ 400000000000000000000000000000000000000 (0 38개)</p><p>그러므로 LimitOrder 컨트랙트의 주소는 0x44로 시작하여야 하며, 테스트에서는 0x4400000000000000000000000000000000000000로 설정해도 아무 문제가 없다.</p><p>그래서 다음과 같이 테스트코드에서 LimitOrder 변수를 생성해준다.</p><pre>LimitOrder limitOrder = LimitOrder(address(0x4400000000000000000000000000000000000000));</pre><p>위에서는 new 키워드가 없으므로, 컨트랙트가 아니며 그냥 LimitOrder 컨트랙트 타입의 변수다.</p><p>그리고 validateHookAddress 함수를 override 하여 빈 함수로 만들고 LimitOrder 컨트랙트를 상속하고 있는 LimitOrderImplementation이라는 컨트랙트를 생성해 준다. 다음과 같이 말이다.</p><p>test/shared/implementation/LimitOrderImplementation.sol</p><pre>contract LimitOrderImplementation is LimitOrder {<br>    constructor(IPoolManager _poolManager, LimitOrder addressToEtch) LimitOrder(_poolManager) {<br>        Hooks.validateHookAddress(addressToEtch, getHooksCalls());<br>    }<br><br>    // make this a no-op in testing<br>    function validateHookAddress(BaseHook _this) internal pure override {}<br>}</pre><p>이렇게 하는 이유는 기존의 LimitOrder 컨트랙트의 valdiateHookAddress 함수를, 오직 테스트 만을 위해 컨트랙트를 수정하지 않기 위함이다.</p><p>그리고 setUp 함수에서 다음과 같이 limitOrder 컨트랙트를 설정해 줄 수 있다.</p><pre>function setUp() public {<br>  ...<br>  vm.record();<br>    LimitOrderImplementation impl = new LimitOrderImplementation(manager, limitOrder);<br>    (, bytes32[] memory writes) = vm.accesses(address(impl));<br>    vm.etch(address(limitOrder), address(impl).code);<br>    // for each storage key that was written during the hook implementation, copy the value over<br>    unchecked {<br>        for (uint256 i = 0; i &lt; writes.length; i++) {<br>            bytes32 slot = writes[i];<br>            vm.store(address(limitOrder), slot, vm.load(address(impl), slot));<br>        }<br>    }<br>...</pre><p>vm.record</p><ul><li>모든 스토리지 읽기 및 쓰기 기록을 시작하도록 지시하는 명령어다.</li><li>LimitOrderImplementation impl = new LimitOrderImplementation(manager, limitOrder), 이 라인에서 스토리지 쓰기를 진행한다.</li></ul><p>(, bytes32[] memory writes) = vm.accesses(address(impl));</p><ul><li>writes 배열에, LimitOrderImplementation에서 쓰기를 한 모든 스토리지 슬롯을 가져올 수 있다.</li></ul><p>vm.etch(address(limitOrder), address(impl).code);</p><ul><li>주소 0x4400000000000000000000000000000000000000에 LimitOrderImplementation.sol 코드를 붙인다.</li></ul><p>for 문</p><ul><li>LimitOrderImplementation를 배포하면서 스토리지 쓰기를 한(eg. poolManager 주소) 것을 limitOrder 주소에도 적용시켜준다. vm.load를 통해서 impl의 slot 값에 해당하는 슬롯에 있는 값을 가져와 같은 슬롯에 저장하는 것이다.</li></ul><p>이렇게 Foundry 환경에서는 LimitOrder 컨트랙트를 생성하지 않고도, 어떤 주소에 코드를 붙이고 slot을 조작할 수 있다.</p><p>setUp 함수를 계속 보자.</p><pre>function setUp() public {<br>  ...<br>  key = PoolKey(currency0, currency1, 3000, 60, limitOrder);<br>  id = key.toId();<br>    manager.initialize(key, SQRT_RATIO_1_1, ZERO_BYTES);<br>  ...</pre><p>Fee는 3000, tickSpacing은 60 그리고 훅은 LimitOrder 컨트랙트로 하는 key 값을 선언한다. 그리고 PoolManager 컨트랙트의 initialize 함수를 통해 해당 풀을 배포할 것이다.</p><p>풀을 배포할 때 인자로는 key 값과, SQRT_RATIO_1_1 그리고 ZERO_BYTES를 인자로 넘겨준다.</p><p>SQRT_RATIO_1_1은 79228162514264337593543950336이다.</p><ul><li>유니스왑에서 tick은 유한한 정수이며 양수 및 음수가 될 수 있다. 가격을 저장할 때 정수 부분에는 64비트를, 분수 부분에는 96비트를 사용하는 유리수인 <a href="https://en.wikipedia.org/wiki/Q_%28number_format%29">Q64.96</a>이라는 고정 소수점 숫자로 sqrt(가격)을 저장한다.</li><li>예를 들어 token x의 reserve가 3 그리고 token y의 reserve가 5라고 가정하면, x의 가격을 sqrtPriceX96의 형태로 변환하는 과정은 다음과 같다.</li></ul><p>=&gt; sqrt(5/3)*2⁹⁶</p><p>테스트케이스에서는 최대한 간단하게 하기 위해 reserve가 1:1라고 가정하고, sqrt(1/1)*2⁹⁶을 가격으로 세팅할 것이다. 그리고 마지막 인자 값은 훅 flag를 체크하고, 콜백 함수로 콜백이 올 때 넘겨주는 값으로, 이 테스트케이스에서는 필요 없으므로 0으로 세팅한다.</p><p>PoolManager의 initialize는 전 편의 “풀 생성”에서 다뤘으므로 참고 바란다. PoolManager의 initialize 함수 호출 후 결과는 다음과 같다.</p><p>slot0 = Slot0({</p><p>sqrtPriceX96: 79228162514264337593543950336,</p><p>tick: 0,</p><p>protocolSwapFee: 0,</p><p>hookSwapFee: 0,</p><p>protocolWithdrawFee: 0,</p><p>hookWithdrawFee: 0</p><p>});</p><p>여기서 tick은 다음 식을 통해 구할 수 있다. tick = log(sqrtPriceX96 / 2⁹⁶)</p><p>=&gt; log(79228162514264337593543950336 / 2⁹⁶) ⇒ 0</p><p>setUp 함수는 다음과 같이 마무리 된다.</p><pre>function setUp() public {<br>  ...    <br>  swapRouter = new PoolSwapTest(manager);<br><br>    token0.approve(address(limitOrder), type(uint256).max);<br>    token1.approve(address(limitOrder), type(uint256).max);<br>    token0.approve(address(swapRouter), type(uint256).max);<br>    token1.approve(address(swapRouter), type(uint256).max);<br>}</pre><p>SwapRouter는 현재 v4-core/contracts/test/PoolSwapTest.sol을 사용하면 된다. 지정가 주문을 넣기 위해서 미리 limitOrder와 swapRouter 컨트랙트를 approve 해주는 것으로 테스트 setUp은 끝난다.</p><h3>지정가 주문 테스트</h3><p>테스트 환경 setUp을 끝내고 이제 지정가 주문 테스트를 진행하겠다. 테스트 시나리오는 최대한 간단하게 했으며 v4-periphery/test/LimitOrder.t.sol을 참고했다. 지정가주문 ⇒ 스왑 ⇒ 출금 이렇게 테스트를 진행하겠다.</p><p>각각 시나리오의 코드는 자세히 다뤘으므로 여기서는 실 데이터를 기반으로 state가 어떻게 변하는지만 다룰 것이다. 참고로 poolManager에서는 각 풀마다 State struct로 state들을 관리한다.</p><p>v4-core/contracts/libraries/Pool.sol</p><pre>struct State {<br>    Slot0 slot0;<br>    uint256 feeGrowthGlobal0X128;<br>    uint256 feeGrowthGlobal1X128;<br>    uint128 liquidity;<br>    mapping(int24 =&gt; TickInfo) ticks;<br>    mapping(int16 =&gt; uint256) tickBitmap;<br>    mapping(bytes32 =&gt; Position.Info) positions;<br>}</pre><p><strong>지정가 주문</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BeyqN7gQ7xLECUiVjZXXA.png" /><figcaption>지정가 주문, 이 그림은 중간 과정을 완전히 생략한 요약본이니 아래 내용을 참고해 주시길 바랍니다</figcaption></figure><pre>function testLimitOrder() public {<br> int24 tickLower = 0;<br> bool zeroForOne = true;<br> uint128 liquidity = 1000000;<br> limitOrder.place(key, tickLower, zeroForOne, liquidity);<br> ...</pre><p>(modifyPoistion ⇒ transferFrom ⇒ settle)</p><p>(1) modifyPoistion</p><p>— PoolManager —</p><p>tickLower가 0이고, zeroForOne이 true라면 tick 범위는 0~0+tickSpacing이 된다. 0~60 tick 범위에 1000000 만큼의 유동성을 제공할 것이다. 현재 tick이 0이므로, token0으로만 유동성을 제공하게 된다.</p><p>feeGrowthGlobal0x128 = 0<br>feeGrowthGlobal1x128 = 0<br>liquidity = 1000000</p><p>updateTick</p><ul><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li></ul><p>tickBitmap.flipTick</p><ul><li>tickBitmap[0] = …00011 (2진수, 앞에 0 254개)</li><li>여기서 [인덱스]는 word로 256비트 단위이고, 한 word 안에서 각 자릿수는 bitPos라고 한다. bitPos는 0부터 시작해 왼쪽으로 갈수록 255까지 증가한다.</li></ul><p>position update</p><ul><li>positions[keccak256(abi.encodePacked(지정가 주문 훅 address, 0, 60))] = { liquidity : 1000000, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 0 }</li></ul><p>return delta.amount0 = 2996</p><ul><li>여기서 2996은 v4-core/contracts/libraries/SqrtPriceMath.sol의 getAmount0Delta 함수로 구해진 값이다.</li><li>amount0Delta = (Liquidity * 2⁹⁶) * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / UpperSqrtPriceX96 / LowerSqrtPriceX96</li><li>= (1000000 * 79228162514264337593543950336) * (79466191966197645195421774833–79228162514264337593543950336 ) / 79466191966197645195421774833 / 79228162514264337593543950336</li><li>= 2996</li></ul><p>(2) transferFrom</p><p>user가 poolManager에게 2996 token0을 transfer</p><p>(3) settle</p><p>reservesOf[token0] = 2996</p><p>델타 값 변화 (modifyPosition + transferFrom &amp; settle)</p><p>modifyPosition</p><ul><li>currencyDelta[지정가 주문 훅 address][token0Address] = 2996</li><li>nonzeroDeltaCount는 0에서 1로 증가</li></ul><p>transferFrom &amp; settle</p><ul><li>currencyDelta[지정가 주문 훅 address][token0Address] = 2996–2996 = 0</li><li>nonzeroDeltaCount 1에서 0으로 감소</li></ul><p>— LimitOrder —</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false,</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total:0,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>이렇게 지정가 주문이 끝나면 다음과 같이 assertion 테스트를 진행할 수 있다.</p><pre>function testLimitOrder() public {<br>  ...<br>  assertTrue(<br>      EpochLibrary.equals(<br>          limitOrder.getEpoch(key, tickLower, zeroForOne),<br>          Epoch.wrap(1)<br>      )<br>  );<br>  assertEq(<br>      manager.getLiquidity(<br>          id,<br>          address(limitOrder),<br>          tickLower,<br>          tickLower + 60<br>      ),<br>      liquidity<br>  );<br>  ...<br>}</pre><p>참고로 epoch는 1부터 값을 저장한다.</p><p><strong>Swap &amp; SwapAfter</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37gVsv8bottwx0IWZ0BJSA.png" /><figcaption>Swap, 이 그림은 중간 과정을 완전히 생략한 요약본이니 아래 내용을 참고해 주시길 바랍니다</figcaption></figure><pre>function testLimitOrder() public {<br> ...<br> swapRouter.swap(<br>            key,<br>            IPoolManager.SwapParams(<br>                false,<br>                1e18,<br>                TickMath.getSqrtRatioAtTick(60)<br>            ),<br>            PoolSwapTest.TestSettings(true, true)<br>        );</pre><p>swapRouter가 PoolManager에 lock을 건다.</p><p>SwapParams는 v4-core/contracts/interfaces/IPoolManager.sol에서 확인할 수 있으며 다음과 같다.</p><pre>struct SwapParams {<br>    bool zeroForOne;<br>    int256 amountSpecified;<br>    uint160 sqrtPriceLimitX96;<br>}</pre><p>zeroForOne이 false이므로, token1을 token0으로 스왑하는 것이다. 그리고 amountSpecified는 1e18으로 설정했고, 현재 풀에는 2996 token0밖에 없다. sqrtPriceLimitX96을 getSqrtRatioAtTick(60)으로 설정했으므로 1e18을 전부 transfer 하지 않고(0~60 사이에 유동성이 1e18만큼 없으므로) 부분 swap이 이루어질 것이다.</p><p>TestSettings는 v4-core/contracts/test/PoolSwapTest.sol에서 확인할 수 있다.</p><pre>struct TestSettings {<br>    bool withdrawTokens;<br>    bool settleUsingTransfer;<br>}</pre><p>withdrawTokens를 true로 설정하면, take 하지 않고 ERC1155를 mint 한다. false는 그 반대다.</p><p>settleUsingTransfer를 true로 설정하면, token transferFrom과 settle을 하게 되고, false로 설정하면 ERC1155를 PoolManager에게 transfer 한다.</p><p>이 테스트에서는 둘 다 true로 설정한다.</p><p>— PoolManager —</p><p>tickBitmap.nextInitializedTickWithinOneWord</p><p>v4-core/contracts/libraries/TickBitmap.sol을 보면</p><pre>function nextInitializedTickWithinOneWord(<br>    mapping(int16 =&gt; uint256) storage self,<br>    int24 tick,<br>    int24 tickSpacing,<br>    bool lte<br>) internal view returns (int24 next, bool initialized) {<br>    unchecked {<br>        int24 compressed = tick / tickSpacing;<br>    ...<br>    (int16 wordPos, uint8 bitPos) = position(compressed + 1);<br>        // all the 1s at or to the left of the bitPos<br>        uint256 mask = ~((1 &lt;&lt; bitPos) - 1);<br>        uint256 masked = self[wordPos] &amp; mask;<br><br>...<br>function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) {<br>    unchecked {<br>        wordPos = int16(tick &gt;&gt; 8);<br>        bitPos = uint8(int8(tick % 256));<br>    }<br>}</pre><p>이렇게 마스크 연산을 통해서 다음 초기화된 tick을 찾는다. zeroForOne이 true로 token0의 가격이 올라가기 때문에, 더 큰 tick을 찾아야 한다.</p><p>현재 tick: 0, word:0, bitPos:1</p><ul><li>comprssed는 0/60 = 0이다. 그리고 compressed에 1을 더하여 wordPos는 0, bitPos는 1이 된다. 여기서 1을 더하는 이유는 더 큰 bitPos 값을 찾을 때 현재 bitPos 값을 제외한다.</li></ul><p>현재 tickBitmap 값: tickBitmap[0] = …00011 (2진수, 앞에 0 254개)</p><ul><li>zeroForOne이 true이기 때문에 현재 1bitPos를 기준으로 자신을 포함한 왼쪽에서 initialized된 tick을 찾는다. 이때 마스크는 ~((1 &lt;&lt; bitPos) — 1) ⇒ 111….1110 이 되고 wordPos &amp; mask 연산을 통해 같은 word 안에 1 bitPos가 초기화되어있는 것을 바로 찾을 수 있다. 1 bitPos에 60 tickSpacing 을 곱해줌으로써 tickNext 값은 60이 된다.</li></ul><p>computeSwapStep</p><ul><li>amountIn = RoundingUp(Liquidity * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / 2⁹⁶)<br>=&gt; 1000000 * (79466191966197645195421774833–79228162514264337593543950336) / 2⁹⁶ = 3005</li><li>amountOut = (Liquidity * 2⁹⁶) * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / UpperSqrtPriceX96 / LowerSqrtPriceX96<br>=&gt; (1000000 * 2⁹⁶) * (79466191966197645195421774833–79228162514264337593543950336) / 79466191966197645195421774833 / 79228162514264337593543950336 = 2995</li><li>feeAmount = RoundingUp(amountIn * 3000 / (1000000–3000)) = 10</li><li>feeGrowthGlobal1X128 = feeAmount * 2¹²⁸ / liquidity = 3402823669209384634633746074317682</li><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }<br>⇒ ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 3402823669209384634633746074317682 }</li></ul><p>델타 값 변화 (swap)</p><ul><li>currencyDelta[swapRouter address][token0Address] = -2995</li><li>currencyDelta[swapRouter address][token1Address] = 3015</li><li>nonzeroDeltaCount 0에서 2로 증가</li></ul><p>AfterSwap 훅 함수 호출</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiHWmw44y83ZfeyuSMuRSw.png" /><figcaption>AfterSwap, 이 그림은 중간 과정을 완전히 생략한 요약본이니 아래 내용을 참고해 주시길 바랍니다</figcaption></figure><p>LimitOrder 컨트랙트가 PoolManager에 lock을 건다.</p><p>lockAcquiredFilled의 modifyPosition을 통해서 0~60 tick 범위에 EpochInfos[epochs[keccack256(abi.encode(key,0,true))]].liquidityTotal = 1000000 만큼 유동성을 제거한다.</p><p>— PoolManager —</p><p>feeGrowthGlobal0x128 = 0</p><p>feeGrowthGlobal1x128 = 0 ⇒ 3402823669209384634633746074317682</p><p>liquidity = 1000000 ⇒ 0</p><p>updateTick</p><ul><li>ticks[0]: { liquidityGross: 1000000, liquidityNet:1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li></ul><p>⇒ ticks[0]: { liquidityGross: 0, liquidityNet:0, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</p><ul><li>ticks[60]: { liquidityGross: 1000000, liquidityNet: -1000000, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 0 }</li></ul><p>⇒ ticks[60]: { liquidityGross: 0, liquidityNet: 0, feeGrowthOutside0X128: 0, feeGrowthOutside1X128: 3402823669209384634633746074317682 }</p><p>tickBitmap.flipTick</p><ul><li>tickBitmap[0] = …00011 (2진수, 앞에 0 254개) ⇒ …00000 (0 256개)</li></ul><p>position update</p><ul><li>positions[keccak256(abi.encodePacked(지정가 주문 훅 address, 0, 60))] = { liquidity : 1000000, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 0 }</li></ul><p>⇒ positions[keccak256(abi.encodePacked(지정가 주문 훅 address, 0, 60))] = { liquidity : 0, feeGrowthInside0LastX128: 0, feeGrowthInside1LastX128: 3402823669209384634633746074317682 }</p><p>feesOwed = 9</p><ul><li>feesOwed1 = (feeGrowthInside1x128 — _self.feeGrowthInside1LastX128) * liquidity / 2¹²⁸</li><li>= (3402823669209384634633746074317682–0) * 1000000 / 340282366920938463463374607431768211456 = 9</li></ul><p>return delta.amount1 = -3004 + (-9) = -3013</p><ul><li>delta.amount1 = -(Liquidity * (UpperSqrtPriceX96 — LowerSqrtPriceX96) / 2⁹⁶) + (-feesOwed)</li><li>= -(1000000 * (79466191966197645195421774833–79228162514264337593543950336 ) / 79228162514264337593543950336) + (-9) = -3013</li></ul><p>— LimitOrder —</p><p>ERC1155 mint</p><ul><li>LimitOrder 주소로 3013만큼 ERC1155 mint</li></ul><p>델타 값 변화 (modifyPosition + mint ERC1155)</p><p>modifyPosition</p><ul><li>currencyDelta[지정가 주문 훅 address][token1Address] = -3013</li><li>nonzeroDeltaCount는 2에서 3로 증가</li></ul><p>mint ERC1155</p><ul><li>currencyDelta[지정가 주문 훅 address][token0Address] = -3013 + 3013 = 0</li><li>nonzeroDeltaCount 3에서 2으로 감소</li></ul><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false, ⇒ true</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total: 0 ⇒ 3013,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>Swap 마무리</p><p>take token0</p><ul><li>reservesOf[token0] = 2996–2995 = 1</li><li>currencyDelta[swapRouter address][token0Address] = -2995 + 2995 = 0</li><li>nonzeroDeltaCount 2에서 1로 감소</li><li>transfer to swapper</li></ul><p>transfer token1 to PoolManager</p><ul><li>reservesOf[token1] = 3015</li></ul><p>settle token1</p><ul><li>currencyDelta[swapRouter address][token1Address] = 3015–3015 = 0</li><li>nonzeroDeltaCount 1에서 0으로 감소</li></ul><p>이렇게 스왑이 끝나면 다음과 같이 assertion 테스트를 진행할 수 있다.</p><pre>function testLimitOrder() public {<br>  ...<br>  assertEq(limitOrder.getTickLowerLast(id), 60);<br>  (, int24 tick, , , , ) = manager.getSlot0(id);<br>  assertEq(tick, 60);<br>  <br>  (<br>      bool filled,<br>      ,<br>      ,<br>      uint256 token0Total,<br>      uint256 token1Total,<br>  <br>  ) = limitOrder.epochInfos(Epoch.wrap(1));<br>  assertTrue(filled);<br>  assertEq(token0Total, 0);<br>  assertEq(token1Total, 3013);<br>  assertEq(<br>      manager.getLiquidity(<br>          id,<br>          address(limitOrder),<br>          tickLower,<br>          tickLower + 60<br>      ),<br>      0<br>  );<br>  ...<br>}</pre><p><strong>출금</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1vW4Oay20vAj9BRF0C9oQ.png" /><figcaption>출금, 이 그림은 중간 과정을 완전히 생략한 요약본이니 아래 내용을 참고해 주시길 바랍니다</figcaption></figure><pre>function testLimitOrder() public {<br> ...<br> limitOrder.withdraw(Epoch.wrap(1), &lt;받을 주소&gt;);<br> ...</pre><p>첫 번째 인자로는 epcoh 인덱스 그리고 두 번째 인자는 받을 주소를 넘겨주면 된다.</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false, ⇒ true</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total: 0 ⇒ 3013 ⇒ 3013–3013 = 0</p><p>liquidityTotal:1000000 ⇒ 1000000–1000000 = 0</p><p>liquidity[msg.sender]:1000000 ⇒ delete liquidity[msg.sender] ⇒ 0</p><p>}</p><p>ERC1155 safeTransferFrom</p><ul><li>LimitOrder 컨트랙트가 가지고 있는 3013개의 ERC1155토큰을 PoolManager에게 전송한다.</li><li>PoolManager는 받은 ERC1155토큰을 모두 burn 시킨다.</li><li>currencyDelta[지정가 주문 훅 address][token0Address] = -3013</li><li>nonzeroDeltaCount 0에서 1로 증가</li></ul><p>Take</p><ul><li>reservesOf[token1] = 3015–3013 = 2</li><li>nonzeroDeltaCount 1에서 0으로 감소</li><li>&lt;받을 주소&gt;에게 3013 token1 전송</li></ul><p>이렇게 출금이 끝나면 다음과 같이 assertion 테스트를 진행할 수 있고 이렇게 마무리 한다.</p><pre>function testLimitOrder() public {<br>  ...<br>  (, , , token0Total, token1Total, ) = limitOrder.epochInfos(<br>      Epoch.wrap(1)<br>  );<br>  <br>  assertEq(token0Total, 0);<br>  assertEq(token1Total, 0);<br>}</pre><p>유니스왑 V4에서 아직 다루지 않은 부분이 많다. 그중에서 EIP-1153 Transient Storage에 대해서 간단히 다루고 마무리를 짓겠다.</p><h3>EIP-1153 : Transient Storage</h3><p>2024년 1월에 있을 이더리움 “Dencun”의 업그레이드 범위에 EIP-1153이 포함되었고, 유니스왑 V4 백서에서도 Transient Storage를 사용하여 가스비를 줄일 것이라고 명시하고 있다. 해당 내용에 대해서 간단하게 다루겠다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*kky-P6v54ZA9PXZ4e-UKzA.png" /><figcaption>Source: <a href="https://twitter.com/pcaversaccio">Pascal Marco Caversaccio</a></figcaption></figure><p>위의 그림처럼 기존의 calldata, memory 그리고 storage 외에 Transient Storage라는 것을 도입한다. Transient Storage는 memory처럼 해당 트랜잭션이 끝날 때 휘발되고, storage(world state)처럼 함수의 scope를 벗어나 전역 scope에서 읽기와 쓰기가 가능하다.</p><p>읽기와 쓰기인 새로운 opcode “tload”와 “tstore”가 새로 추가가 될 예정이며, “sload”와 “sstore”보다 95%나 싼 가스비를 소모한다. 이는 다음과 같은 상황에서 엄청 유용하게 쓰일 수 있다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-C8NJkWqYEnKiujO366Ew.png" /></figure><p>바로 유니스왑 V4에서 자주 쓰이는 델타 값이다. 델타는 결국 값 0에서 시작해서 0으로 끝난다. 그러므로 트랜잭션이 끝날 때 휘발되어도 아무 문제가 없다. 그리고 해당 값은 하나의 함수 내에서만 쓰이는 값이 아니라 여러 함수에서 쓰는 값이므로, world state처럼 전역 scope를 가져야 한다. 그러므로 델타값은 Transient Storage에 저장하여 사용하면 딱이다. 이렇게 불필요한 storage 연산들을 없애 엄청난 가스비를 절약할 수 있다.</p><p>*추후 TONDEX 프로젝트에서 유니스왑V3를 V4로 마이그레이션하는 작업을 하게 될 것이다. 지정가 주문뿐만 아니라 훅 컨트랙트를 사용하여 유동성 제공자들에게 혜택이 많이 갈 수 있는 새로운 수수료 정책을 도입할 것이며, 새로운 디파이 상품에 대한 아이디어를 모색하고 개발해 나갈 것이다.</p><p>이것으로 유니스왑V4 지정가 주문 아티클을 마무리합니다. 감사합니다.</p><p>Reference</p><ul><li>유니스왑 V4 백서 (<a href="https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf">https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf</a>)</li><li>v4-core (<a href="https://github.com/Uniswap/v4-core">https://github.com/Uniswap/v4-core</a>)</li><li>v4-periphery (<a href="https://github.com/Uniswap/v3-periphery">https://github.com/Uniswap/v3-periphery</a>)</li><li>유니스왑 블로그 (<a href="https://blog.uniswap.org/uniswap-v4">https://blog.uniswap.org/uniswap-v4</a>)</li><li>EIP-1153 (<a href="https://eips.ethereum.org/EIPS/eip-1153">https://eips.ethereum.org/EIPS/eip-1153</a>)</li><li>Foundry Docs (<a href="https://book.getfoundry.sh/">https://book.getfoundry.sh/</a>)</li></ul><p>포스팅을 작성하는 데에 도움을 주신 Kevin, Zena 님에게 감사를 표합니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d46e01108a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokamak-network/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%EB%B6%84%EC%84%9D-%EC%8B%9C%EB%A6%AC%EC%A6%88-part-2-6d46e01108a6">Uniswap V4 지정가 주문 훅 part 2</a> was originally published in <a href="https://medium.com/tokamak-network">Tokamak Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uniswap V4 지정가 주문 훅 part 1]]></title>
            <link>https://medium.com/tokamak-network/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%ED%9B%85-part-1-1075a8c9e654?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1075a8c9e654</guid>
            <category><![CDATA[uniswap]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[tokamak-network]]></category>
            <category><![CDATA[onther]]></category>
            <category><![CDATA[research]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 05:05:46 GMT</pubDate>
            <atom:updated>2023-11-21T07:37:03.325Z</atom:updated>
            <content:encoded><![CDATA[<h4>스마트 컨트랙트 소스코드 레벨 분석</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*D4HaLuVVTduYWsy7UY9VMg.png" /><figcaption>유니스왑 V4 로고(Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p>유니스왑 V4는 훅(hook)이란 것을 도입하여 유니스왑 풀들과의 상호작용 과정의 다양한 지점에서 커스텀 로직이 실행될 수 있도록 했다. 유니스왑 V4 공식 블로그에서는 동적 수수료, 온 체인 지정가 주문 그리고 대규모 거래를 작은 거래로 쪼개어 장기간에 걸쳐 처리되는 TWAMM(Time-weighted Automated Market Maker) 등을 훅의 예로 들고 있다. 유니스왑 랩스는 유니스왑을 단순한 DEX(Decentralized Exchange)가 아닌 맞춤형 플러그인과 프로세스를 만들 수 있는 금융 인프라로 보고 있다고 한다.</p><p>추후 타이탄 메인넷에 올라갈 TONDEX라는 프로젝트에서 유니스왑 V4의 훅을 사용하여 지정가 주문을 구현할 예정이다. 현재 유니스왑 깃허브에 드래프트 버전의 Core와 Periphery 레포지토리가 공개되어 있다. 테스트는 파운드리(Foundry) 프레임워크를 사용했다. 지정가 주문이 어떻게 온 체인으로 이루어지는지, V3와 어떻게 달라졌는지 드래프트 버전의 코드를 읽고 분석한 내용을 이 글에서 다루겠다.</p><p>*V3에 대한 이해도가 어느 정도 있어야 읽기 편하다.</p><p>영문 버전은 아래 링크에서 확인하실 수 있습니다:</p><ul><li><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-1-586233620584">Uniswap V4 Limit Order Hook part 1</a></li><li><a href="https://medium.com/onther-tech/uniswap-v4-limit-order-hook-part-2-c130997a4481">Uniswap V4 Limit Order Hook part 2</a></li></ul><p>목차는 다음과 같다.</p><ul><li>V3에서의 지정가 주문</li><li>V4 컨트랙트 구성도</li><li>V4 훅 플로우</li><li>훅 컨트랙트 설정 및 CREATE2 배포</li><li>풀 생성</li><li>지정가 주문 넣기</li></ul><h3><strong>V3에서의 지정가 주문</strong></h3><p>코드를 보기 전에 유니스왑 V3에서 지정가 주문이 어떻게 이루어지는지 그림 예시를 통해서 알아보겠다.</p><p>(1) 현재 풀 상태</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdnQfdAMUCm6ssRicNUMYQ.png" /></figure><p>현재 tick이 85176이라고 가정하겠다. tick 이란 log_{sqrt(1.0001)}(sqrt(가격))과 같다. 이 그래프에서 높이는 유동성을 의미하며, current tick을 기준으로 왼쪽은 USDC 유동성으로 채워져있고, 오른쪽은 ETH 유동성으로 채워져있다.</p><p>이제 사용자가 ETH가 가격이 올라갈 것으로 예상한다. 정확히는 tick이 85680을 넘을 것이라고 예상하고 있다. 그럼 85620~85680의 tick 범위에 ETH로 유동성을 제공할 것이다. 다음 그림과 같아진다.</p><p>(2) 85620~85680 범위에 ETH로 유동성을 넣은 상태</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po1_X5P6DlE2iMCU5Hnb7Q.png" /></figure><p>여기서 85620은 85680–60을 통해서 구한 값이다. 왜 60을 뺐는지 알려면 tickSpacing이라는 것을 알고 있어야 한다. 현재 유니스왑 V3에서 유동성을 추가하는 페이지를 가보면 다음과 같은 Fee Tier를 볼 수 있을 것이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*gKbzMa90K8GWc-hdTiLxfg.png" /></figure><p>각각의 값은 해당 풀에서 거래할 때 발생하는 수수료를 나타낸다. 그리고 각 값마다 tickSpacing 이란 것이 매칭되어 고정되어 있다.</p><p>0.01% Fee Tier ⇒ 1 TickSpacing</p><p>0.05% Fee Tier ⇒ 10 TickSpacing</p><p>0.3% Fee Tier ⇒ 60 TickSpacing (예시)</p><p>1% Fee Tier ⇒ 200 TickSpacing</p><p>여기서 TickSpacing은 tick 사이의 거리를 설정하는 tick 간격이다. 이 거리가 넓을수록 가스 효율이 높아지고 정확성은 떨어진다. Tick을 tickSpacing의 배수 단위로 인덱싱하여, 해당 tick에 유동성이 있는지 없는지 검사한다. 그리고 정확성을 이유로 current tick의 값에는 적용되지 않는다.</p><p>0.05%~1% Fee Tier와 각각의 TickSpacing은 <a href="https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/UniswapV3Factory.sol#L26-L31C34">v3-core/contracts/UniswapV3Factory.sol</a>에 하드코딩 되어 있으며, 0.01%는 유니스왑 거버넌스 투표를 통해서 결정되어 활성화되었다.</p><p>(3) 현재 tick이 85680까지 올라간 상태</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKc_t74McaPUdJSvdyNP8w.png" /></figure><p>위 그림을 보면 USDC를 팔고 ETH를 사 가는 스왑이 많이 일어났고, 현재 tick은 예상대로 85680에 도달했다. 그럼 아까 제공한 ETH 유동성이 USDC 유동성으로 바뀌게 되고, USDC를 돌려받을 수 있는 상태가 된다.</p><p>그럼 이때 유저(EOA)는 v3-periphery/contracts/NonfungiblePositionManganager 컨트랙트를 통해서 decreaseLiquidity와 collect 함수를 encode 해서 인자로 설정하고 Multicall 함수를 호출한다. 각각 무엇을 하는지 간단하게 설명하겠다.</p><p>v3-core/contracts/libraries/Position.sol을 보면 Info struct를 확인할 수 있다.</p><pre>// info stored for each user&#39;s position<br>struct Info {<br>    // the amount of liquidity owned by this position<br>    uint128 liquidity;<br>    // fee growth per unit of liquidity as of the last update to liquidity or fees owed<br>    uint256 feeGrowthInside0LastX128;<br>    uint256 feeGrowthInside1LastX128;<br>    // the fees owed to the position owner in token0/token1<br>    uint128 tokensOwed0;<br>    uint128 tokensOwed1;<br>}</pre><p>decreaseLiquidity</p><ul><li>feeGrowthInsideLast와 liquidity 값을 현재 tick을 기준으로 새로 계산하여 tokensOwed 값을 업데이트한다. tokensOwed는 collectable amount이다.</li></ul><p>collect</p><ul><li>tokensOwed 만큼 claim 하는 함수이다.</li></ul><p>하지만 사용자는 해당 풀의 tick이 변경되는 것을 계속 모니터링하다가 직접 decreaseLiquidity와 collect 함수를 호출해야 한다. 현재 스마트 컨트랙트는 다른 스마트 컨트랙트를 지켜보다가 혼자서 트랜잭션을 트리거 할 수 없는 구조이기 때문이다. 오프 체인 봇을 사용하는 경우도 있다.</p><p>하지만 이번 V4에서는 지정가 주문 훅을 사용하여 완전히 온체인에서 지정가 주문을 가능하게 만들었다.</p><h3>V4 컨트랙트 구성도</h3><p>유니스왑 V4는 V3와 유사하게 <a href="https://github.com/Uniswap/v4-core">v4-core</a>와 <a href="https://github.com/Uniswap/v4-periphery">v4-periphery</a> 레포지토리로 나누어 컨트랙트들을 관리한다.</p><p>전체적인 컨트랙트 구성도는 다음과 같다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxO6S8eGM0CBaRW36alPoA.png" /><figcaption>컨트랙트 구성도</figcaption></figure><p>V4에서는 V3와 다르게, PoolManager라는 컨트랙트가 v4-core 레포지토리에 존재하고, initialize, swap 그리고 modifyPosition 등의 로직들은 모두 v4-core/contracts/libraries/Pool.sol 라이브러리에 구현되어 있다. v4-core의 PoolManager 컨트랙트는 어떻게 보면 v3-periphery의 NonfungiblePositionManager 컨트랙트와 유사하지만, 모든 코어 로직에 사용되는 state들을 스토리지로 가지고 있다.</p><p>그리고 V4에서는 User-defined Value Types를 적극 활용하고 types 폴더에 각 타입을 정의해놨다. 예를 들어 각 토큰을 address가 아닌 Currency라는 User-defined Value Type을 정의하고 사용하고 있다.</p><p>v4-core/contracts/types/Currency.sol</p><pre>type Currency is address;<br><br>using {greaterThan as &gt;, lessThan as &lt;, equals as ==} for Currency global;<br>function equals(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) == Currency.unwrap(other);<br>}<br>function greaterThan(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) &gt; Currency.unwrap(other);<br>}<br>function lessThan(Currency currency, Currency other) pure returns (bool) {<br>    return Currency.unwrap(currency) &lt; Currency.unwrap(other);<br>}<br>/// @title CurrencyLibrary<br>/// @dev This library allows for transferring and holding native tokens and ERC20 tokens<br>library CurrencyLibrary {<br>    using CurrencyLibrary for Currency;<br>  ...</pre><p>이런 식으로 타입을 정의해 주면, 해당 타입에는 멤버 함수가 하나도 없다. 그래서 &gt;, &lt; 그리고 ==처럼 기본적인 연산자 사용이 불가능하여 위와 같이 equals, greaterThan 그리고 lessThan 함수를 구현하고, using for global 키워드를 사용하여 전역 scope에서 사용할 수 있도록 했다. 각 함수를 보면 unwrap을 통해서 Currency에서 address로 타입을 변환할 수 있고, wrap을 통해서 address에서 Currency로 타입을 변환할 수 있다.</p><p>v4-periphery를 보면 훅 컨트랙트들 밖에 없다. 이 훅 컨트랙트들은 모두 abstract 컨트랙트인 BaseHook을 상속하고 구현되어 있지 않은 함수를 오버라이드 하여 구현한다. 그리고 IPoolManager 인터페이스를 사용하여 PoolManager 컨트랙트와 상호작용한다. 아직 완성된 레포지토리가 아니며, V3처럼 positionManager 컨트랙트가 생길 수 있다.</p><h3>V4 훅 플로우</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*eAw6t8YqL_OKtFXrIGOJiA.png" /><figcaption>훅 플로우(Source: <a href="https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf">유니스왑 V4 백서</a>)</figcaption></figure><p>위 그림은 스왑 전후로 커스텀 로직 훅을 실행하는 플로우를 보여준다. 스왑 전에 flag를 체크하여 True 면 beforeSwap 훅을 실행하고, 스왑 후에도 afterSwap flag를 체크하여 True 면 afterSwap 훅을 실행시키고 스왑을 끝내게 된다.</p><p>델타라는 값이 0이 되기만 하면 훅에서 정말 어떤 커스텀 로직이든 수행이 가능하다(뒤에서 델타가 무슨 값인지 살펴보겠다). 심지어 악의적인 훅도 개발되어 풀로 만들어질 수 있다. 참고로 V4에서는 각 풀마다 하나의 훅 컨트랙트를 가질 수 있다.</p><p>v4-core/contracts/types/PoolKey.sol의 PoolKey struct를 한번 보자.</p><pre>/// @notice Returns the key for identifying a pool<br>struct PoolKey {<br>    /// @notice The lower currency of the pool, sorted numerically<br>    Currency currency0;<br>    /// @notice The higher currency of the pool, sorted numerically<br>    Currency currency1;<br>    /// @notice The pool swap fee, capped at 1_000_000. The upper 4 bits determine if the hook sets any fees.<br>    uint24 fee;<br>    /// @notice Ticks that involve positions must be a multiple of tick spacing<br>    int24 tickSpacing;<br>    /// @notice The hooks of the pool<br>    IHooks hooks;<br>}</pre><p>V3에서는 token0, token1의 주소와 fee 이렇게 3가지 값을 가지고 풀들을 식별했다. 위에서 설명했듯이 총 4개의 Fee Tier가 있으며 TickSpacing과 각각 매칭되어 고정되어 있다. 그러므로 같은 token0과 token1을 가지고 최대 4개의 풀을 만들 수 있었다.</p><p>V4에서는 다르다. fee와 tickSpacing이 세트가 아니며, hooks라는 값이 추가되었다. 그러므로 총 5가지의 값을 가지고 풀들을 식별하며 셀 수 없을 정도로 많은 풀들이 만들어질 수 있다. 예를 들어 tickSpacing이 61로도 설정이 가능하다.</p><p>현재 smart-order-router는 다음 그림과 같이 스왑시에 최적의 경로를 찾아준다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*r34Pxspo9NTbpjHoYLODPQ.png" /><figcaption>유니스왑 V3 스왑시 멀티 경로</figcaption></figure><p>하지만 V4로 업그레이드되면서 악의적인 훅을 가진 풀들도 존재할 수 있고, 무수히 많은 서로 다른 훅을 가진 풀들의 스왑 결과 값인 amountOut을 계산하기에는 너무나 비효율적일 것이다. 훅이 없는 풀들만 지원을 해주거나(그래도 너무 많다), 신뢰할 수 있는 기관에서 개발했고 Audit(감사)를 받은 훅이 있는 풀들만 지원해 주는 어떠한 정책이 생길 것으로 생각한다. 또한 <a href="https://blog.uniswap.org/how-uniswapv4-uniswapx-work-together">UniswapX</a>를 적극 활용할 것이라고 기대된다.</p><h3>훅 컨트랙트 설정 및 CREATE2 배포</h3><p>지정가 주문을 본격적으로 다루기 전에, 훅 컨트랙트에 어떤 flag를 어떻게 설정하는지 살펴보겠다.</p><p>위에서 언급했듯이 모든 훅 컨트랙트는 abstract 컨트랙트인 BaseHook을 상속하고 구현되어 있지 않은 함수를 오버라이드 하여 구현한다. 그중 하나의 함수가 getHooksCalls이다. 먼저 지정가 주문 컨트랙트에서 해당 함수를 보자.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function getHooksCalls() public pure override returns (Hooks.Calls memory) {<br>    return Hooks.Calls({<br>        beforeInitialize: false,<br>        afterInitialize: true,<br>        beforeModifyPosition: false,<br>        afterModifyPosition: false,<br>        beforeSwap: false,<br>        afterSwap: true,<br>        beforeDonate: false,<br>        afterDonate: false<br>    });<br>}</pre><p>이 함수를 통해서, flag의 종류를 알 수 있다. “initialize”(풀 초기화), “modifyPosition”(포지션 업데이트), “swap” 그리고 “donate” 전후로 flag를 설정하여 커스텀 로직을 실행할 수 있다.</p><p>여기서 “donate”는 V3에는 없는 함수다. 해당 함수는 Pool 컨트랙트에 기부하여 feeGrowthGlobal(전역 수수료) 값을 올려, 해당 풀의 모든 유동성 제공자들이 혜택을 받을 수 있는 구조로 되어 있다. 이렇게 새로운 수수료 체계를 구축할 수 있다. V4에서는 무수히 많은 풀들이 생겨날 것이고, donate와 같은 함수를 활용하여 유동성 제공자들이 수수료를 많이 벌 수 있는 풀에 유동성이 자연스럽게 모일 것이다.</p><p>다시 위의 코드로 돌아와, afterInitialize와 afterSwap의 flag에만 true로 설정되어 있는 것을 확인할 수 있다. 그리고 BaseHook 컨트랙트의 생성자 함수를 보면 아래와 같이 validateHookAddress라는 함수가 있다.</p><p>v4-periphery/contracts/BaseHook.sol</p><pre>constructor(IPoolManager _poolManager) {<br>    poolManager = _poolManager;<br>    validateHookAddress(this);<br>}</pre><p>BaseHook 컨트랙트는 Hooks라는 라이브러리를 import 하고 있으며 validateHookAddress 함수는 Hooks 라이브러리에 구현되어 있다.</p><p>v4-core/contracts/libraries/Hooks.sol</p><pre>uint256 internal constant BEFORE_INITIALIZE_FLAG = 1 &lt;&lt; 159;<br>uint256 internal constant AFTER_INITIALIZE_FLAG = 1 &lt;&lt; 158;<br>uint256 internal constant BEFORE_MODIFY_POSITION_FLAG = 1 &lt;&lt; 157;<br>uint256 internal constant AFTER_MODIFY_POSITION_FLAG = 1 &lt;&lt; 156;<br>uint256 internal constant BEFORE_SWAP_FLAG = 1 &lt;&lt; 155;<br>uint256 internal constant AFTER_SWAP_FLAG = 1 &lt;&lt; 154;<br>uint256 internal constant BEFORE_DONATE_FLAG = 1 &lt;&lt; 153;<br>uint256 internal constant AFTER_DONATE_FLAG = 1 &lt;&lt; 152;<br>...<br>function validateHookAddress(IHooks self, Calls memory calls) internal pure {<br>    if (<br>        calls.beforeInitialize != shouldCallBeforeInitialize(self)<br>            || calls.afterInitialize != shouldCallAfterInitialize(self)<br>            || calls.beforeModifyPosition != shouldCallBeforeModifyPosition(self)<br>            || calls.afterModifyPosition != shouldCallAfterModifyPosition(self)<br>            || calls.beforeSwap != shouldCallBeforeSwap(self) || calls.afterSwap != shouldCallAfterSwap(self)<br>            || calls.beforeDonate != shouldCallBeforeDonate(self) || calls.afterDonate != shouldCallAfterDonate(self)<br>    ) {<br>        revert HookAddressNotValid(address(self));<br>    }<br>}<br>...<br>function shouldCallBeforeInitialize(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_INITIALIZE_FLAG != 0;<br>}<br>function shouldCallAfterInitialize(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_INITIALIZE_FLAG != 0;<br>}<br>function shouldCallBeforeModifyPosition(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_MODIFY_POSITION_FLAG != 0;<br>}<br>function shouldCallAfterModifyPosition(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_MODIFY_POSITION_FLAG != 0;<br>}<br>function shouldCallBeforeSwap(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_SWAP_FLAG != 0;<br>}<br>function shouldCallAfterSwap(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_SWAP_FLAG != 0;<br>}<br>function shouldCallBeforeDonate(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; BEFORE_DONATE_FLAG != 0;<br>}<br>function shouldCallAfterDonate(IHooks self) internal pure returns (bool) {<br>    return uint256(uint160(address(self))) &amp; AFTER_DONATE_FLAG != 0;<br>}</pre><p>위의 코드에서 shouldCall… 로 시작하는 함수는 매번 훅 flag를 체크할 때 사용되는 함수이므로 자주 보일 것이다.</p><p>자 validateHookAddress 함수의 첫 번째 인자인 self는 지정가 주문 컨트랙트의 주소이며, 두 번째 calls 인자는 위에서 살펴본 getHooksCalls 함수의 결괏값이다. getHookscalls 함수의 결괏값과 shouldCall… 로 시작하는 함수의 결괏값을 비교하여 다른 것이 하나라도 있다면 revert를 시키고 있다.</p><p>shouldCall… 로 시작하는 함수들을 보면 전부 훅 컨트랙트 주소에 &amp; 연산을 하여, 특정 비트 자리가 1로 설정되어 있는지를 검사하고 있다. 위에서 afterInitialize와 afterSwap flag만을 설정했으므로, 주소 맨 뒤의 8비트 중에서, 1&lt;&lt;158 자리와 1&lt;&lt;154 자리만 1로 설정되어 있어야 하고 나머지는 0으로 설정되어 있어야 한다.</p><p>즉 주소를 이진수로 표현했을 때 제일 높은 8자리는, 01000100으로 설정되어 있어야 한다. 그리고 주소를 16진수로 나타냈을 때는 0x44..로 시작하는 주소가 될 것이다. 그러므로 임의의 주소로 배포하면 안 되고, CREATE2를 통해 8비트는 훅 flag에 맞는 값으로 설정해 줘야 한다.</p><p>CREATE2는 생성자 주소, 컨트랙트의 바이트코드, constructor 인자 값 그리고 salt 값을 가지고 미리 주소를 계산해 볼 수 있다. 그러므로 구현이 다 끝난 후에 생성자 주소, 바이트코드 그리고 constructor 인자 값은 고정해두고, 반복문을 돌면서 salt 값을 바꿔주어 01000100으로 시작하는 주소를 만들어 내야 한다(brute force). 마치 비트코인의 PoW처럼 말이다.</p><h3>풀 생성</h3><p>풀을 생성하는 과정에서 V3와 큰 차이가 있다. V3에서는 Factory 패턴을 사용하여 모든 풀들을 새로운 컨트랙트로 배포했지만 V4에서는 싱글톤 패턴을 사용한다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asV2rgFONzXYymAvPMmosw.png" /><figcaption>V4 싱글톤 패턴(Source: <a href="https://blog.uniswap.org/uniswap-v4">Uniswap Labs Blog</a>)</figcaption></figure><p>위의 그림은 ETH를 DAI로 스왑하는 과정에 경로가 여러 개일 때를 나타낸다. 왼쪽을 보면 transfer가 무려 6번이나 일어난다. 하지만 오른쪽의 싱글톤 패턴을 보면 transfer는 2번으로 끝이 난다. 이렇게 가스비를 크게 절약할 수 있다. 오른쪽 그림에서 각 토큰 페어는 컨트랙트가 아니라 v4-core/contracts/PoolManager 컨트랙트의 맵핑 변수인 pools로 관리된다. key 값은 다음과 같이 계산되어 진다.</p><p>v4-core/contracts/types/PoolId.sol</p><pre>type PoolId is bytes32;<br>function toId(PoolKey memory poolKey) internal pure returns (PoolId) {<br>    return PoolId.wrap(keccak256(abi.encode(poolKey)));<br>}</pre><p>위에서 살펴본 PoolKey struct의 값들을 encode 하고 해쉬한다.</p><p>다음은 풀을 생성하는 동작에 대한 시퀀스 다이어그램이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*-_PBcPEt4o0bpZjA7P8V6Q.png" /><figcaption>풀 생성, 시퀀스 다이어그램</figcaption></figure><p>모든 코드를 라인 바이 라인으로 다루고 싶지만 글이 너무 길어질 수 있기 때문에, 해당 포스팅의 주제인 지정가 주문과 크게 관련 없는 부분은 생략할 것이다. PoolManager 컨트랙트의 initialize 함수를 보자.</p><p>v4-core/contracts/PoolManager.sol</p><pre>function initialize(PoolKey memory key, uint160 sqrtPriceX96 ...<br>{<br>  ...<br>  tick = pools[id].initialize(sqrtPriceX96, protocolSwapFee, hookSwapFee, protocolWithdrawFee, hookWithdrawFee);<br><br>    if (key.hooks.shouldCallAfterInitialize()) {<br>        if (<br>            key.hooks.afterInitialize(msg.sender, key, sqrtPriceX96, tick)<br>                != IHooks.afterInitialize.selector<br>        ) { <br>            revert Hooks.InvalidHookResponse();<br>        }<br>    }<br><br>    emit Initialize(id, key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks);<br>}</pre><p>v4-core/contracts/libraries/Pool.sol</p><pre>function initialize(<br>    State storage self,<br>    uint160 sqrtPriceX96,<br>    uint8 protocolSwapFee,<br>    uint8 hookSwapFee,<br>    uint8 protocolWithdrawFee,<br>    uint8 hookWithdrawFee<br>) internal returns (int24 tick) {<br>    if (self.slot0.sqrtPriceX96 != 0) revert PoolAlreadyInitialized();<br>    tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);<br>    self.slot0 = Slot0({<br>        sqrtPriceX96: sqrtPriceX96,<br>        tick: tick,<br>        protocolSwapFee: protocolSwapFee,<br>        hookSwapFee: hookSwapFee,<br>        protocolWithdrawFee: protocolWithdrawFee,<br>        hookWithdrawFee: hookWithdrawFee<br>    });<br>}</pre><p>먼저 Pool.sol 라이브러리에서 Slot0의 구조를 볼 수 있고, 아래 V3와는 필드들이 다른 것을 확인할 수 있다.</p><p>v3-core/contracts/UniswapV3Pool.sol</p><pre>struct Slot0 {<br>        uint160 sqrtPriceX96;<br>        int24 tick;<br>        uint16 observationIndex;<br>        uint16 observationCardinality;<br>        uint16 observationCardinalityNext;<br>        uint8 feeProtocol;<br>        bool unlocked;<br>    }</pre><p>V4에서는 observation 관련 변수들이 사라졌다. 즉 오라클 기능이 default가 아니다. V3에서는 오라클을 사용하지 않는 경우에도 포지션의 업데이트가 필요할 때 오라클 관련 변수들을 업데이트하느라 불필요하게 가스비가 낭비되었다. V4에서 오라클 기능이 필요하다면 훅으로 구현하여 풀을 배포하면 된다.</p><p>그리고 V3의 feeProtocol은 V4에서 protocolSwapFee와 protocolWithdrawFee로 나뉜다. 참고로 V3에서는 protocolFee가 항상 0이었고, 거버넌스 투표를 통해 바뀔 수 있다. V4에서 hookSwapFee와 hookWithdrawFee라는 변수가 추가되었다. 이는 swap이나 withdraw 시에 수수료를 매길 수 있다. 이는 훅 개발자가 이득을 취할 수 있는 부분이며, 사용자가 원하지 않으면 해당 풀에서 거래를 안 하면 된다.</p><p>tick과 sqrtPriceX96은 그대로지만 unlocked라는 변수가 V4에서는 없다. V4에서는 lock, 콜백 패턴 그리고 델타라는 값을 사용하고 뒤에서 자세히 다루겠다.</p><p>v4-core의 poolManager 컨트랙트의 initialize 함수를 보면, pool을 초기화한 후에 shouldCallAfterInitialize 함수를 통해서 flag를 체크하고 훅 컨트랙트의 afterInitialize 함수를 호출한다.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function afterInitialize(address, PoolKey calldata key, uint160, int24 tick, bytes calldata)<br>    external<br>    override<br>    poolManagerOnly<br>    returns (bytes4)<br>{<br>    setTickLowerLast(key.toId(), getTickLower(tick, key.tickSpacing));<br>    return LimitOrder.afterInitialize.selector;<br>}</pre><p>함수는 정말 간단하다. 만약에 tickSpacing이 60이고 현재 tick이 80이라고 가정하자. 그럼 내림 연산을 하여 60이 tickLowerLast 값으로 저장된다. tickLowerLast라는 값은 뒤에서 지정가 주문이 체결될 때 사용되는 값으로, tick이 변경될 때 항상 업데이트되는 값이다.</p><p>그리고 모든 훅 함수는 마지막에 항상 selector를 반환하고 poolManager 컨트랙트는 hook의 response가 훅 함수의 selector 인지 항상 확인한다.</p><h3>지정가 주문 넣기</h3><p>다음은 지정가 주문 넣기 동작에 대한 시퀀스 다이어그램이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*lo3aF6Az4t49YF5wiPIMJA.png" /><figcaption>지정가 주문 넣기, 시퀀스 다이어그램</figcaption></figure><p>본격적으로 지정가 주문 넣는 것을 다루기 전에 먼저 지정가 주문 자료구조를 보겠다.</p><pre>struct EpochInfo {<br>    bool filled;<br>    Currency currency0;<br>    Currency currency1;<br>    uint256 token0Total;<br>    uint256 token1Total;<br>    uint128 liquidityTotal;<br>    mapping(address =&gt; uint128) liquidity;<br>}<br><br>mapping(bytes32 =&gt; Epoch) public epochs;<br>mapping(Epoch =&gt; EpochInfo) public epochInfos;<br>...<br>function getEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne) public view returns (Epoch) {<br>    return epochs[keccak256(abi.encode(key, tickLower, zeroForOne))];<br>}</pre><p>struct 명을 보면 order나 limitOrder가 아닌 Epoch라는 단어를 쓰고 있다. Epoch이라는 단어는 블록체인에서 보통 간격이나 시간 단위의 뜻으로 사용된다. 여기서는 tickSpacing 만큼의 간격을 가지는 tick range(범위)를 뜻한다. 그래서 같은 범위에 여러 명의 사용자들이 지정가 주문을 넣을 수 있고, EpochInfo struct 안에 liquidity 매핑 변수로 각 사용자들의 유동성 값을 유지하고 있다. 그리고 같은 범위에 있는 지정가 주문들은 모두 한 번에 처리가 되는 구조다.</p><p>epochInfo의 key 값을 구하는 함수가 getEpoch이다. 여기서 zeroForOne은 방향, 즉 롱 포지션인지 숏 포지션인지를 판단하는 boolean 값이다. 이렇게 같은 동일한 키로 여러 사용자들의 지정가 주문이 있을 수 있다.</p><p>이제 지정가 주문을 넣는 place 함수를 살펴보겠다. 이 함수를 다루면서 콜백 패턴과 델타라는 값에 대해서 다룰 것이다.</p><p>v4-periphery/contracts/hooks/examples/LimitOrder.sol</p><pre>function place(PoolKey calldata key, int24 tickLower, bool zeroForOne, uint128 liquidity)<br>    external<br>    onlyValidPools(key.hooks)<br>{<br>    if (liquidity == 0) revert ZeroLiquidity();<br><br>    poolManager.lock(<br>        abi.encodeCall(this.lockAcquiredPlace, (key, tickLower, zeroForOne, int256(uint256(liquidity)), msg.sender))<br>    );<br>  ...<br>}<br>...<br>function lockAcquiredPlace(<br>    PoolKey calldata key,<br>    int24 tickLower,<br>    bool zeroForOne,<br>    int256 liquidityDelta,<br>    address owner<br>) external selfOnly {<br>    BalanceDelta delta = poolManager.modifyPosition(<br>        key,<br>        IPoolManager.ModifyPositionParams({<br>            tickLower: tickLower,<br>            tickUpper: tickLower + key.tickSpacing,<br>            liquidityDelta: liquidityDelta<br>        }),<br>        ZERO_BYTES<br>    );<br><br>    if (delta.amount0() &gt; 0) {<br>        if (delta.amount1() != 0) revert InRange();<br>        if (!zeroForOne) revert CrossedRange();<br>        // TODO use safeTransferFrom<br>        IERC20Minimal(Currency.unwrap(key.currency0)).transferFrom(<br>            owner, address(poolManager), uint256(uint128(delta.amount0()))<br>        );<br>        poolManager.settle(key.currency0);<br>    } else {<br>        if (delta.amount0() != 0) revert InRange();<br>        if (zeroForOne) revert CrossedRange();<br>        // TODO use safeTransferFrom<br>        IERC20Minimal(Currency.unwrap(key.currency1)).transferFrom(<br>            owner, address(poolManager), uint256(uint128(delta.amount1()))<br>        );<br>        poolManager.settle(key.currency1);<br>    }<br>}</pre><p>place 함수는 바로 poolManager 컨트랙트의 lock 함수를 호출하면서 lockAcquiredPlace 함수와 인자 값들을 인코딩 하여 lock 함수의 인자로 넘겨주고 있다.</p><p>참고로 abi.encodeCall은 function 포인터에 대한 호출을 인코딩한다. 결과는 흔히 사용하는 encodeWithSelector와 같지만 첫 번째 파라미터가 함수 selector가 아닌 function 포인터다.</p><p>PoolManager의 lock 함수에서 LimitOrder의 lockAcquired 함수로 콜백이 온다. 그리고 modifyPosition과 settle 함수 등을 통해서 poolManager 컨트랙트와 상호작용을 하게 된다.</p><p>V4에서 PoolManager 컨트랙트와 상호작용을 통해 state를 변경시키려면 다음과 같은 패턴을 가지게 된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfmlrUP2IwQR6IZzHB0-oQ.png" /><figcaption>콜백 패턴(Source: <a href="https://mirror.xyz/albertlin.eth/zE3lxVNZTxXwsLH0XpggUO_H_fmQMjmlEaFbMUaPYaA">Exploring the Core Mechanism of UniswapV4</a>)</figcaption></figure><p>이렇게 lock을 획득하고, poolManager와의 컨트랙트와의 상호작용을 끝내고 lock에서 벗어날 때 델타라는 값이 0이면 된다. 잠금 기간 동안 PoolManager가 콜백 컨트랙트에게 빚지거나, 콜백 컨트랙트가 PoolManager에게 빚져 갚아야 하는 값을 델타라고 한다. 즉 lock에서 벗어날 때는 서로 빚진 것이 없어야 트랜잭션이 성공한다.<br>PoolManager와 상호작용하는 함수들은, swap, modifyPosition, donate, take, settle 그리고 mint 함수들이 있다.</p><p>위의 lockAcquiredPlace 함수를 보면 poolManager 컨트랙트의 modifyPosition 함수는 델타라는 값을 반환한다. 참고로 V3와 다르게 V4에서는 modifyPosition이 private 함수가 아닌 external 함수로, 콜백 컨트랙트(locker)에서 바로 호출이 가능하다. 포지션 정보를 업데이트하고 서로 빚진 거를 갚기만 하면 되는 것이다.</p><p>poolManager에서 반환해 주는 델타라는 값은 다음과 같이 되어 있다.</p><pre>function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        balanceDelta :=<br>            or(shl(128, _amount0), and(0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff, _amount1))<br>    }<br>}</pre><p>델타는 int256이며, 왼쪽 128비트는 amount0을 그리고 오른쪽 128비트는 amount1을 나타낸다. 그리고 amount0과 amount1함수로 각 값을 구할 수 있다.</p><pre>function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        _amount0 := shr(128, balanceDelta)<br>    }<br>}<br><br>function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        _amount1 := balanceDelta<br>    }<br>}</pre><p>여기서 amount0과 amount1은 한 토큰쌍의 각 amount다. 그리고 값이 양수이면 콜백 컨트랙트가 PoolManager에게 빚진 것이고, 음수이면 PoolManager가 콜백 컨트랙트에게 빚진 것이다.</p><p>다시 LimitOrder.sol의 lockAcquiredPlace 함수를 보면, amount0이나 amount1이 양수인지 체크하고, 양수인 경우에는 PoolManager에게 해당 토큰을 빚진 만큼 transfer 해주고 settle 함수를 호출하게 된다. modifyPosition, transfer 그리고 settle 함수를 통해서 PoolManager의 델타 값을 0에서 0으로 만들어주는 것이다. 이제 poolManager 안에서는 델타값을 어떻게 처리하는지 보겠다.</p><p>v4-core/contracts/PoolManager.sol</p><pre>/// @inheritdoc IPoolManager<br>function lock(bytes calldata data) external override returns (bytes memory result) {<br>    lockData.push(msg.sender);<br><br>    // the caller does everything in this callback, including paying what they owe via calls to settle<br>    result = ILockCallback(msg.sender).lockAcquired(data);<br>    if (lockData.length == 1) {<br>        if (lockData.nonzeroDeltaCount != 0) revert CurrencyNotSettled();<br>        delete lockData;<br>    } else {<br>        lockData.pop();<br>    }<br>}<br>...<br>function _accountDelta(Currency currency, int128 delta) internal {<br>    if (delta == 0) return;<br><br>    address locker = lockData.getActiveLock();<br>    int256 current = currencyDelta[locker][currency];<br>    int256 next = current + delta;<br><br>    unchecked {<br>        if (next == 0) {<br>            lockData.nonzeroDeltaCount--;<br>        } else if (current == 0) {<br>            lockData.nonzeroDeltaCount++;<br>        }<br>    }<br><br>    currencyDelta[locker][currency] = next;<br>}</pre><p>이렇게 lock 함수를 통해서 lockData 변수에 콜백 컨트랙트 주소를 넣는다.</p><p>그리고 _accountDelta 함수는 modifyPosition이나 swap과 같은 함수를 통해서 currencyDelta 변수에 콜백 컨트랙트 주소와 토큰 주소를 key 값으로 하여 얼마를 빚졌는지에 대한 값을 업데이트한다. 그리고 해당 값이 0이 아니라면 nonzeroDeltaCount라는 변수를 증가시킨다. 만약에 next가 0으로 계산되어 빚진 값을 갚은 것이라면 nonzeroDeltaCount 변수를 감소시킨다.</p><p>lock 함수를 보면, 콜백 컨트랙트의 lockAcquired 함수가 끝나고 lock 함수가 끝날 때, lockData의 nonzeroDeltaCount가 0이 아니라면 revert 시키고 0이면 lock 함수는 성공하여 트랜잭션이 성공하게 된다.</p><p>다시 지정가 주문의 lockAcquiredPlace 함수로 돌아와, modifyPosition → transferFrom → settle 이렇게 3번 PoolManager와 상호작용하면서 델타 값이 변하는 과정을 정리하겠다.</p><p>(1) modifyPosition</p><ul><li>지정가 주문에서 modifyPosition은 currency0과 currency1 중에서 하나를 골라 한쪽으로 유동성을 제공하는 함수이다. 여기서는 currency0으로 유동성을 제공했다고 가정하겠다.</li><li>currency[&lt;limitOrderAddress&gt;][&lt;currency0Address&gt;] = +x (양수)</li><li>nonzeroDeltaCount는 1이 된다.</li></ul><p>(2) transferFrom</p><ul><li>currency0을 x 만큼 poolManager 컨트랙트에게 transfer</li></ul><p>(3) settle</p><pre>function settle(Currency currency) external payable override noDelegateCall onlyByLocker returns (uint256 paid) {<br>        uint256 reservesBefore = reservesOf[currency];<br>        reservesOf[currency] = currency.balanceOfSelf();<br>        paid = reservesOf[currency] - reservesBefore;<br>        // subtraction must be safe<br>        _accountDelta(currency, -(paid.toInt128()));<br>    }</pre><ul><li>여기서 reservesOf[&lt;currency0Address&gt;]를 통해서 마지막으로 저장했던 값을 불러온다. 그리고 현재 poolManager의 currency0 balance 값을 불러와 업데이트한다.</li><li>마지막으로 저장했던 값이랑 현재 업데이트된 값을 비교하여 차액인 x를 음수로 만들고 _accountDelta 함수에 인자로 넣어준다.</li><li>currency[&lt;limitOrderAddress&gt;][&lt;currency0Address&gt;] = +x -x = 0이 되고 nonzeroDeltaCount는 0이 되어 lock에서 벗어날 수 있다.</li></ul><p>그리고 modifyPosition 함수는 delta를 계산하여 delta를 반환해 준다는 것, 그리고 여러 가지 수수료 정책을 고려하는 부분을 빼고는 V3와 큰 차이점이 없다. 쌓인 fee를 업데이트해 주는 방식과 tickBitmap을 사용하여 tick들을 초기화시켜주는 로직이 같다.</p><p>추가적으로, lockData 관련 함수들은 v4-core/contracts/libraries/LockDataLibrary.sol에 구현되어 있다.</p><pre>library LockDataLibrary {<br>uint256 private constant OFFSET = uint256(keccak256(&quot;LockData&quot;));<br><br>/// @dev Pushes a locker onto the end of the queue, and updates the sentinel storage slot.<br>function push(IPoolManager.LockData storage self, address locker) internal {<br>    // read current value from the sentinel storage slot<br>    uint128 length = self.length;<br>    unchecked {<br>        uint256 indexToWrite = OFFSET + length; // not in assembly because OFFSET is in the library scope<br>        /// @solidity memory-safe-assembly<br>        assembly {<br>            // in the next storage slot, write the locker<br>            sstore(indexToWrite, locker)<br>        }<br>        // update the sentinel storage slot<br>        self.length = length + 1;<br>    }<br>}<br>...</pre><p>이 라이브러리는 큐(Queue)를 위한 커스텀 스토리지를 구현하고 있다. 마치 큐처럼 push와 pop 함수가 구현되어 있다. 그리고 uint256(keccak256(“LockData”))의 slot부터 locker의 address를 저장한다. 참고로 uint256(keccak256(“LockData”))의 값은 53391651520919458808831464411208423921832704174599079787929421271630035089670 이다.</p><p>그리고 v4-core/contracts/libraries/Pool.sol을 보면 TickInfo struct는 다음과 같다.</p><pre>struct TickInfo {<br> uint128 liquidityGross;<br> int128 liquidityNet;<br> // fee growth per uint of liquidity on the _other_ side of this tick (relative to the current tick) only has relative meaning, not absolute - the value depends on when the tick is initialized<br> uint256 feeGrowthOutside0x128;<br> uint256 feeGrowthOutside1x128;<br>}</pre><p>여기서 liquidityGross와 liquidityNet 두 개를 합치면 256bits이므로 한 slot을 차지하게 된다. 그리고 assembly 블록에서 shift 연산을 통해서 각각의 값을 불러오고 업데이트를 시켜준다.</p><p>v4-core/contracts/libraries/Pool.sol에서 updateTick함수를 보면 알 수 있다.</p><pre>function updateTick(State storage self, int24 tick, int128 liquidityDelta, bool upper)<br>    internal<br>    returns (bool flipped, uint128 liquidityGrossAfter)<br>{<br>    TickInfo storage info = self.ticks[tick];<br><br>    uint128 liquidityGrossBefore;<br>    int128 liquidityNetBefore;<br>    assembly {<br>        // load first slot of info which contains liquidityGross and liquidityNet packed<br>        // where the top 128 bits are liquidityNet and the bottom 128 bits are liquidityGross<br>        let liquidity := sload(info.slot)<br>        // slice off top 128 bits of liquidity (liquidityNet) to get just liquidityGross<br>        liquidityGrossBefore := shr(128, shl(128, liquidity))<br>        // shift right 128 bits to get just liquidityNet<br>        liquidityNetBefore := shr(128, liquidity)<br>    }<br>    liquidityGrossAfter = liquidityDelta &lt; 0<br>        ? liquidityGrossBefore - uint128(-liquidityDelta)<br>        : liquidityGrossBefore + uint128(liquidityDelta);<br><br>    flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);<br><br>    if (liquidityGrossBefore == 0) {<br>        // by convention, we assume that all growth before a tick was initialized happened _below_ the tick<br>        if (tick &lt;= self.slot0.tick) {<br>            info.feeGrowthOutside0X128 = self.feeGrowthGlobal0X128;<br>            info.feeGrowthOutside1X128 = self.feeGrowthGlobal1X128;<br>        }<br>    }<br>    // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)<br>    int128 liquidityNet = upper ? liquidityNetBefore - liquidityDelta : liquidityNetBefore + liquidityDelta;<br>    assembly {<br>        // liquidityGrossAfter and liquidityNet are packed in the first slot of `info`<br>        // So we can store them with a single sstore by packing them ourselves first<br>        sstore(<br>            info.slot,<br>            // bitwise OR to pack liquidityGrossAfter and liquidityNet<br>            or(<br>                // liquidityGross is in the low bits, upper bits are already 0<br>                liquidityGrossAfter,<br>                // shift liquidityNet to take the upper bits and lower bits get filled with 0<br>                shl(128, liquidityNet)<br>            )<br>        )<br>    }<br>}</pre><p>이런 식으로 storage 연산을 줄여, 가스비를 아낄 수 있다. liquidityGross와 liquidityNet은 V3와 똑같이 사용되는 값이다.</p><p><a href="https://medium.com/onther-tech/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%EB%B6%84%EC%84%9D-%EC%8B%9C%EB%A6%AC%EC%A6%88-part-2-6d46e01108a6">다음 포스팅</a>에서 지정가 주문을 처리하고 withdraw, 그리고 추가적으로 다루지 않은 EIP-1153과 Foundry 환경에서 훅 컨트랙트를 테스트하는 것 등에 대해서 다루겠다.</p><p>Reference</p><ul><li>유니스왑 V4 백서 (<a href="https://github.com/Uniswap/v4-core/blob/main/docs/whitepaper-v4.pdf">https://github.com/Uniswap/v4-core/blob/main/whitepaper-v4-draft.pdf</a>)</li><li>v4-core (<a href="https://github.com/Uniswap/v4-core">https://github.com/Uniswap/v4-core</a>)</li><li>v4-periphery (<a href="https://github.com/Uniswap/v3-periphery">https://github.com/Uniswap/v3-periphery</a>)</li><li>유니스왑 블로그 (<a href="https://blog.uniswap.org/uniswap-v4">https://blog.uniswap.org/uniswap-v4</a>)</li></ul><p>포스팅을 작성하는 데에 도움을 주신 Aaron, Kevin, Zena 님에게 감사를 표합니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1075a8c9e654" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tokamak-network/uniswap-v4-%EC%A7%80%EC%A0%95%EA%B0%80-%EC%A3%BC%EB%AC%B8-%ED%9B%85-part-1-1075a8c9e654">Uniswap V4 지정가 주문 훅 part 1</a> was originally published in <a href="https://medium.com/tokamak-network">Tokamak Network</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UniswapV4 LimitOrder Test (Draft Ver)]]></title>
            <link>https://medium.com/@usgeeus/uniswapv4-limitorder-test-4908e264169d?source=rss-9e5e41e966c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4908e264169d</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[limit-order]]></category>
            <category><![CDATA[periphery]]></category>
            <category><![CDATA[uniswap-v4]]></category>
            <category><![CDATA[cores]]></category>
            <dc:creator><![CDATA[Justin Gee]]></dc:creator>
            <pubDate>Wed, 04 Oct 2023 00:58:06 GMT</pubDate>
            <atom:updated>2023-11-15T05:45:22.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*SpcU8cQNDMg7E7Tv.png" /></figure><p>어떻게 지정가 주문이 이루어지는지 보겠다.</p><pre>function testSwapAcrossRange() public {<br> int24 tickLower = 0;<br> bool zeroForOne = true;<br> uint128 liquidity = 1000000;<br> limitOrder.place(key, tickLower, zeroForOne, liquidity);<br><br> ...<br> //swap<br> //withdraw</pre><p>먼저 tickLower = 0, 그리고 zeroForOne = true, liquidity = 1000000으로 지정가 주문을 넣겠다. 자세한 지정가 주문을 넣는 설명은 전 포스팅에서 확인할 수 있다.</p><p>zeroForOne이 true이므로, token0으로 0~60 range에 2996 토큰을 제공한다.</p><p>ticks[0] : {</p><p>liquidityGross : 1000000,</p><p>liquidityNet : 1000000</p><p>}</p><p>ticks[60] : {</p><p>liquidityGross : 1000000,</p><p>liquidityNet: -1000000</p><p>}</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false,</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total:0,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>이어서 swap을 해서 current tick을 움직이고 지정가 주문이 이루어지는 것을 보자.</p><pre>...<br>swapRouter.swap(<br> key,<br> IPoolManager.SwapParams(false, 1e18, TickMath.getSqrtRatioAtTick(60)),<br> PoolSwapTest.TestSettings(true,true)<br>);<br>assertEq(limitOrder.getTickLowerLast(id), 60);<br>(, int tick,,,,) = manager.getSlot0(id);<br>assertEq(tick, 60);</pre><p>여기서 PoolManager의 swap function을 바로 호출하지 않는 것은 PoolManager의 swap function에 onlyByLocker라는 modifier 때문인데, 다른 컨트랙트에서 PoolManager의 lock을 획득하고 나서 swap이 가능하다.</p><p>SwapParams 는 다음과 같다.</p><pre>struct SwapParams {<br> bool zeroForOne;<br> int256 amountSpecified;<br> uint160 sqrtPriceLimitX96;<br>}</pre><p>zeroForOne이 false이므로, token1을 token0으로 스왑하는 것이다. 그리고 1e18만큼</p><p>amountIn으로 명시했다. 그리고 sqrtPriceLimitX96으로 getSqrtRatioAtTick(60) 값을 넣었으니 현재 tick이 0인데 최대 60까지 tick이 변할 것이고, amountIn이 모두 스왑되는 것이 아닌 부 swap이 이루어질 것이다.</p><p>그리고 마지막 인자값인 TestSettings는 어떻게 사용되는지 이따가 볼 것이다. swapRouter의 swap 함수를 보자.</p><p>PoolSwapTest.sol</p><pre>function swap(PoolKey memory key, IPoolManager.SwapParams memory params, TestSettings memory testSettings) external payable returns (BalanceDelta detla) {<br> delta = abi.decode(manager.lock(abi.encode(CallbackData(msg.sender, testSettings, key, params))), (BalanceDelta));<br>...이어서</pre><p>manager 컨트랙트의 lock 함수를 바로 호출한다. 해당 함수를 보자.</p><p>PoolManager.sol</p><pre>function lock(bytes calldata data) external override returns (bytes memory result) {<br> lockData.push(msg.sender);<br><br> // the caller does everything in this callback, including paying what they owe via calls to settle<br> result = ILockCallback(msg.sender).lockAcquired(data);<br><br> if (lockData.length == 1) {<br>  if (lockData.nonzeroDeltaCount != 0) revert CurrencyNotSettled();<br>  delete lockData;<br> } else {<br>  lockData.pop();<br> }<br>}</pre><p>먼저 lockData에 swapRouter 컨트랙트 주소를 push한다. 여기서 lockData는 실제 배열이 아닌 struct이고 push함수는 라이브러리 함수다. 해당 함수에 대해서 전 포스팅에서 다루었다.</p><p>여기서 바로 swapRouter의 lockAcquired함수를 호출한다.</p><p>PoolSwapTest.sol</p><pre>function lockAcquired(bytes calldata rawData) external returns (bytes memory) {<br> required(msg.sender == address(manager));<br><br> CallbackData memory data = abi.decode(rawData, (CallbackData));<br><br> BalanceDelta delta = manager.swap(data.key, data.params);<br> ...이어서</pre><p>lockAcquired함수에서 다시 manager 컨트랙트의 swap 함수를 호출한다. 파라미터로 PoolKey와 params에는 { zeroForOne: false, amountSpecified: 1e18, sqrtPriceLimitX96: getSqrtRatioAtTick(60)}의 값이 들어간다. 해당 함수를 보자.</p><p>PoolManager.sol</p><pre>function swap(PoolKey memory key, IPoolManager.SwapParams memory params) external override noDelegateCall onlyByLocker returns (BalanceDelta delta) {<br> if (key.hooks.shouldCallBeforeSwap()) {<br>  if (key.hooks.beforeSwap(msg.sender, key, params) != IHooks.beforeSwap.selector) {<br>   revert Hooks.InvalidHookResponse();<br>  }<br> }<br><br> // Set the total swap fee, either through the hook or as the static fee set an initialization.<br> uint24 totalSwapFee;<br> if (key.fee.isDynamicFee()) {<br>  totalSwapFee = IDynamicFeeManager(address(key.hooks)).getFee(key);<br>  if (totalSwapFee &gt;= 1000000) revert FeeTooLarge();<br> } else {<br>  //clear the top 4 bits since they may be flagged for hook fees<br>  totalSwapFee = key.fee.getStaticFee();<br> }<br>...이어서</pre><p>onlyByLocker 모디파이어는 전 포스팅을 참고 바란다. 그리고 지정가 주문 훅에는 shouldCallBeforeSwap에 해당하지 않는다. 그리고 해당 풀은 다이나믹 풀이 아니므로 getStaticFee함수를 호출한다. 해당 함수를 보자.</p><pre>function getStaticFee(uint24 self) internal pure returns(uint24) {<br> return self &amp; STATIC_FEE_MASK;<br>}</pre><p>STATIC_FEE_MASK는 0x0FFFFF이다. 여기서 self는 3000이다. binary로 표현하면 101110111000. 그리고 0x0FFFFF을 binary로 표현하면 0x000011111111111111111111이다. 그러므로 3000 그대로 반환이 된다.</p><p>이어서 swap 함수를 보자.</p><p>PoolManager.sol swap function</p><pre>...이어서<br>uint256 feeForProtocol;<br>uint256 feeForHook;<br>Pool.SwapState memory state;<br>PoolId id = key.toId();<br>(delta, feeForProtocol, feeForHook, state) = pools.[id].swap(<br> Pool.SwapParams({<br>  fee: totalSwapFee,<br>  tickSpacing: key.tickSpacing,<br>  zeroForOne: params.zeroForOne,<br>  amountSpecified: params.amountSpecified,<br>  sqrtPriceLimitX96: params.sqrtPriceLimitX96<br> })<br>);</pre><p>여기서 totalSwapFee는 3000, tickSpacing은 60, amountSpecified는 1e18, sqrtPriceLimitX96은 getSqrtRatioAtTick(60)이 된다. 그리고 state를 return받는데 해당 자료구조를 미리 보자.</p><pre>// the top level state of the swap, the results of which are recorded in storage at the end<br>struct SwapState {<br> // the amount remaining to be swapped in/out of the input/output asset<br> int256 amountSpecifiedRemaining;<br> // the amount already swapped out/in of the output/input asset<br> int256 amountCalculated;<br> // current sqrt(price)<br> uint160 sqrtPriceX96;<br> // the tick associated with the current price<br> int24 tick;<br> // the global fee growth of the input token<br> uint256 feeGrowthGlobalX128;<br> // the current liquidity in range<br> uint128 liquidity;<br>}</pre><p>이 결과들이 마지막에 storage에 저장될 것 이다.</p><p>Pool 컨트랙트의 swap 함수를 보자.</p><pre>/// @dev Executes a swap against the state, and returns the amount deltas of the pool<br>function swap(State storage self, SwapParams memory params) internal returns (BalanceDelta result, uint256 feeForProtocol, uint256 feeForHook, SwapState memory state) {<br> if (params.amountSpecified == 0) revert SwapAmountCannotBeZero();<br><br> Slot0 memory slot0Start = self.slot0;<br> if (slot0Start.sqrtPriceX96 == 0) revert PoolNotInitialized();<br> if (params. zeroForOne) {<br>  if (params.sqrtPriceLimitX96 &gt;= slot0Start.sqrtPriceX96) { <br>   revert PriceLimitAlreadyExceeded(slot0Start.sqrtPriceX96, params.sqrtPriceLimitX96);<br>  }<br>  if (params.sqrtPriceLimitX96 &lt;= TickMath.MIN_SQRT_RATIO) {<br>   revert PriceLimitOutOfBounds(params.sqrtPriceLimitX96);<br>  }<br> } else {<br>  if (params.sqrtPriceLimitX96 &lt;= slot0Start.sqrtPriceX96) {<br>   revert PriceLimitAlreadyExceeded(slot0Start.sqrtPriceX96, params.sqrtPriceLimitX96);<br>  }<br>  if (params.sqrtPriceLmitX96 &gt;= TickMath.MAX_SQRT_RATIO) {<br>   revert PriceLimitOutOfBounds(params.sqrtPriceLimitX96);<br>  }<br> }<br><br> SwapCache memory cache = SwapCache({<br>  liquidityStart: self.liquidity,<br>  protocolFee: params.zeroForOne ? (slot0Start.protocolSwapFee % 16) : (slot0Start.protocolSwapFee &gt;&gt; 4),<br>  hookFee: params.zeroForOne ? (slot0Start.hookSwapFee % 16) : (slot0Start.hookSwapFee &gt;&gt; 4)<br> });<br><br> bool exactInput = params.amountSpecified &gt; 0;<br><br> state = SWapState({<br>  amountSpecifiedRemaining: params: amountSpecified,<br>  amountCalculated:0,<br>  sqrtPriceX96: slot0Start.sqrtPriceX96,<br>  tick: slot0Start.tick,<br>  feeGrowthGlobalX128: params.zeroForOne ? self.feeGrowthGlobal0X128 : self.feeGrowthGlobal1X128,<br>  liquidity: cache.liquidityStart<br> });<br> StepComputations memory step;<br>...while 이어서</pre><p>swap 함수에서 while 문에 들어가기 전 까지 코드다.</p><p>먼저 amountSpecified가 0이면 revert가 난다. 그리고 exactInput인지는 amountSpecified가 0보다 큰지 체크한다. exactOutput일 때는 amountSpecified가 음수일 것이다.</p><p>그리고 현재 pool이 initialize되었는지, zeroForOne과 sqrtPriceLimitX96값이 잘 설정되었는지 체크한다.</p><p>cache값에는, 해당 pool의 liquidity:1000000, protocolFee:0, hookFee:0 의 값을 대입한다.</p><p>그리고 state에는, amountSpecifiedRemaining: 1e18, amountCalculated:0, sqrtPriceX96: SQRT_RATIO_1_1 (79228162514264337593543950336), tick: 0, feeGrowthGlobalX128:0, liquidity: 1000000 의 값을 대입한다.</p><p>그리고 state는 현재 swap의 상태를 반영하는 변수이고, step은 반복문의 one iteration의 상태를 반영하는 변수이다.</p><p>이이서 Pool.sol의 swap function을 보자.</p><pre>//continue swapping as long as we haven&#39;t used the entire input/output and haven&#39;t reached the price limit<br>while (state.amountSpeicifedRemaining != 0 &amp;&amp; state.sqrtPriceX96 != params.sqrtPriceLimitX96) {<br> step.sqrtPriceStartX96 = state.sqrtPriceX96;<br><br> (step.tickNext, step.initialized) = self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, params.zeroForOne);<br>...이어서</pre><p>먼저 다음에 초기화된 tick을 찾자. TickBitmap.sol</p><pre>//function nextInitializedTickWithinOneWord(<br> mapping(int16 =&gt; uint256) storage self,<br> int24 tick,<br> int24 tickSpacing,<br> bool lte<br>) internal view returns (int24 next, bool initialized) {<br> unchecked {<br>  int24 compressed = tick / tickSpacing;<br>  if (tick &lt; 0 &amp;&amp; tick % tickSpacing != 0) compressed --;<br>  if (lte) {<br>   (int wordPos, uint8 bitPos) = position(compressed);<br>   // all the 1s at or to the right of the current bitPos<br>   uint256 mask = (1 &lt;&lt; bitPos) - 1 + (1 &lt;&lt; bitPos);<br>   uint256 masked = self[wordPos] &amp; mask;<br><br>   // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word<br>   initialized = masked != 0;<br>   // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick<br>   next = initialized ? (compressed - int24(uint24(bitPos - BitMath.mostSignificantBit(masked)))) * tickSpacing : (compressed - int24(uint24(bitPos))) * tickSpacing;<br> } else {<br>  // start from the word of the next tick, since the current tick state doesn&#39;t matter<br>  (int16 wordPos, uint8 bitPos) = position(compressed + 1);<br>  // all the 1s at or to the left of the bitPos<br>  uint256 mask = ~((1 &lt;&lt; bitPos) - 1);<br>  uint256 masked = self[wordPos] &amp; mask;<br><br>  // if there are no initialized ticks to the left of the current tick, return leftmost in the word<br>  initialized = masked != 0;<br>  // overflow/underflow is possible, but prevented externally by limiting bot tickSpacing and tick<br>  next = initialized ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;<br> }<br>}</pre><p>여기서 comprssed는 0/60 = 0 이다. 그리고 wordPos는 0, bitPos는 1이다.</p><p>0이 아니라 bitPos가 1인 이유는 더 큰 bitPos값을 찾을 때 현재 bitPos값을 제외하기 때문이다. 반대로 더 적은 bitPos값을 찾을 때 현재 bitPos값을 포함해서 찾는다. 그리고 tick 60에 initialized되어 있으므로, initialized는 true이고 next = (0 + 1 + (1–1)) * 60 = 60이다. 여기서 leastSignificantBit가 1인 것은 전 posting에서 다루었다.</p><p>다시 Pool.sol의 swap function으로 돌아가자.</p><pre>(step.tickNext, step.initialized) = self.tickBitmap.nextInitializedTickWithinOneWord(state.tick, params.tickSpacing, params.zeroForOne); //60, true<br><br>// ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds<br>if (step.tickNext &lt; TickMath.MIN_TICK) {<br>    step.tickNext = TickMath.MIN_TICK;<br>} else if (step.tickNext &gt; TickMath.MAX_TICK) {<br>    step.tickNext = TickMath.MAX_TICK;<br>}<br><br>// get the price for the next tick<br>step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);<br><br>// compute values to swap to the target tick, price limit, or point where input/output amount is exhausted<br>(state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(<br> state.sqrtPriceX96,<br> (<br>  params.zeroForOne<br>   ? step.sqrtPriceNextX96 &lt; params.sqrtPriceLimitX96<br>   : step.sqrtPriceNextX96 &gt; params.sqrtPriceLimitX96<br> ) ? params.sqrtPriceLimitX96 <br>  : step.sqrtPriceNextX96,<br> state.liquidity,<br> state.amountSpecifiedRemaining,<br> params.fee<br>);<br>...</pre><p>여기서 MIN_TICK과 MAX_TICK의 범위를 벗어나지 않는지 먼저 체크한다.</p><p>그리고 step.sqrtPriceNextX96는 getSqrtRatioAtTick(60) = 79466191966197645195421774833의 값이 된다.</p><p>그리고 SwapMath.computeSwapStep의 파라미터 값으로는 {</p><p>sqrtRatioCurrentX96 : state.sqrtPriceX96 : 79228162514264337593543950336 (현재 slot0값)</p><p>sqrtRatioTargetX96: step.sqrtPriceNextX96 : TickMath.getSqrtRatioAtTick(60) (아까 구한 다음 초기화된 틱)</p><p>liquidity: state.liquidity (현재 liquidity 1000000)</p><p>state.amountSpecifiedRemaining: 1e18,</p><p>params.fee: 3000 } 이 된다.</p><p>SwapMath.computeSwapStep 함수를 보자.</p><pre>function computeSwapStep(<br> uint160 sqrtRatioCurrentX96,<br> uint160 sqrtRatioTargetX96,<br> uint128 liquidity,<br> int245 amountRemaining,<br> uint24 feePips<br>) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount) {<br> bool zeroForOne = sqrtRatioCurrentX96 &gt;= sqrtREatioTargetX96;<br> bool exactIn = amountRemaining &gt;= 0;<br><br> if (exactIn) {<br>  uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);<br>  amountIn = zeroForOne<br>   ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)<br>   : SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioTargetX96, liquidity, true);<br>  if (amountRemainingLessFee &gt;= amountIn) {<br>   sqrtRatioNextX96 = sqrtRatioTargetX96;<br>  } else {<br>   sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(<br>    sqrtRatioCurrentX96, liquidity, amountRemainingLessFee, zeroForOne<br>   );<br>  }<br> } else {<br>  ...생략<br> }<br>...</pre><p>zeroForOne은 false다. 왜냐하면, 가격이 올라가기 때문. 그리고 exactIn은 true가 된다. 그래서 아래 else는 일단 생략했다.</p><p>여기서 amountRemainingLessFee는 1e18 * 997 / 1000 이다. 즉 fee를 미리 뺀 값이다.</p><p>그리고 getAmount1Delta함수는 0~60의 tick range에 1000000 liquidity를 token1 amount로 계산해준다. 아래 식에서 델타y가 token1이고, sqrt(P)는 getSqrtRatioAtTick(60) — getSqrtRatioAtTick(0)이다. 그리고 L은 Liquidity이다. 실제로 계산해보면 amountIn은 3005이다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*UIpABCtrT8rcmqS39YbG4w.png" /></figure><p>그리고 amountRemainingLessFee와 amountIn의 대소 비교를 한다. 이번 케이스에서는 amountRemainingLessFee가 더 크다. 그러므로 sqrtRatioNextX96에 sqrtRatioTargetX96을 바로 대입한다.</p><p>만약에 amountIn이 더 작다면, sqrtRatioNextX96은 getSqrtRatioAtTick(60) ~ getSqrtRatioAtTick(0) 사이에서 찾게 된다. 하지만 이번 테스트케이스에서는 바로 getSqrtRatioAtTick(60)을 대입해준다.</p><p>이어서 보자.</p><p>SwapMath.computeSwapStep</p><pre>bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;<br><br>//get the input/output amounts<br>if(zeroForOne) {<br> ...생략<br>} else {<br> amountIn = max &amp;&amp; exactIn<br>  ? amountIn<br>  : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);<br> amountOut = max &amp;&amp; !exactIn<br>  ? amountOut<br>  : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);<br>}<br><br>// cap the output amount to not exceed the remaining output amount<br>if(!exactIn &amp;&amp; amountOut &gt; uint256(-amountRemaining)) {<br> amountOut = uint256(-amountRemaining);<br>}<br><br>if (exactIn &amp;&amp; sqrtRatioNextX96 != sqrtRatioTargetX96) {<br> // we didn&#39;t reach the target, so take the remainder of the maximum input as fee<br> feeAmount = uint256(amountRemaining) - amountIn;<br>} else {<br> feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);<br>}</pre><p>여기서 max는 true고 zeroForOne은 false 그리고 exactIn은 true다. 그러므로 amountIn은 그대로 amountIn이고, amountOut은 아래 식(getAmount0Delta)을 통해서 구할 수 있다. amountOut은 2995가 된다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*uFNPzZ15FJxrlV-Owrl0CQ.png" /></figure><p>그리고 feeAmount에는 amountIn * 3000 / 997000 으로 계산한다. 결과값은 10이다.</p><p>그래서 다시 Pool.sol의 swap함수로 돌아오면…</p><p>(state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount)에 방금 계산 값들이 대입된다. 이어서 함수를 보자.</p><p>Pool.sol</p><pre>...<br>if (exactInput) {<br> // safe because we test that amountSpecified &gt; amountIn + feeAmount in SwapMath<br> unchecked {<br>  state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();<br> }<br> state.amountCalculated = state.amountCalculated - step.amountOut.toInt256();<br>} else {<br> ...생략<br>}<br><br>// if the protocol fee is on, calculate how much is owed, decrementfeeAmount, and increment protocolFee<br>if (cache.protocolFee &gt; 0) {<br> //A: calculate the amount of hte fee that should go to the protocol<br> uint256 delta = step.feeAmount / cache.protocolFee;<br> //A: subtract it from the regular fee and add it to the protocol fee<br> unchecked {<br>  step.feeAmount -= delta;<br>  feeForProtocol += delta;<br> }<br>}<br>if (cache.hookFee &gt; 0) {<br> //step.feeAmount has already been updated to account for the protocol fee<br> uint256 delta = step.feeAmount / cache.hookFee;<br> unchecked {<br>  step.feeAmount -= delta;<br>  feeForHook += delta;<br> }<br>}</pre><p>여기서 state.amountSpecifiedRemaining의 값은 1e18 -= (3005 + 10)이 되고, amountCalculated은 -3015가 된다.</p><p>그리고 현재 protocolFee와 hookFee는 없으므로, 생략한다.</p><p>이어서 함수를 보자.</p><pre>// update global fee tracker<br>if (state.liquidity &gt; 0) {<br> unchecked {<br>  state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);<br> }<br>}<br><br>//shift tick if we reached the next price<br>if(state.sqrtPriceX96 == step.sqrtPriceNext96) {<br> // if the tick is initialized, run the tick transition<br> if (step.initialized) {<br>  int128 liquidityNet = Pool.crossTick(<br>   self,<br>   step.tickNext,<br>   (params.zeroForOne ? state.feeGrowthGlobalX128 : self.feeGrowthGlobal0x128),<br>   (params.zeroForOne ? self.feeGrowthGlobal1X128 : state.feeGrowthGlobalX128));<br>  // if we&#39;re moving leftward, we interpret liquidityNet as the opposite sign<br>  // safe because liquidityNet cannot be type(int128).min<br>  unchecked {<br>   if (params.zeroForOne) liquidityNet = -liquidityNet;<br>  }<br>  <br>  state.liquidity = liquidityNet &lt; 0<br>   ? state.liquidity - uint128(-liquidityNet)<br>   : state.liquidity + uint128(liquidityNet);<br> }<br> unchecked {<br>  state.tick = params.zeroForOne ? step.tickNext - 1 : step.tickNext;<br> }<br>} else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {<br> // recompute unless we&#39;re on a lower tick boundrary (i.e. already transitioned ticks), and haven&#39;t moved<br> state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);<br>}</pre><p>먼저 feeGrowthGlobal변수를 업데이트 시켜준다. 이 값은 어느 포지션에 쌓인 fee를 계산할 때 사용되는 값이다.</p><p>그리고 tick 60에 liquidityNet의 값을 가져오게 되는데 그 값은 -1000000이다. 초반에 언급했으며 상세한 내용은 전 포스팅을 참고하길 바란다.</p><p>그래서 state.liquidity는 1000000 이므로, 1000000–1000000 = 0으로 업데이트 시켜준다.</p><p>그리고 zeroForOne이 true이면 tickNext에 1을 빼도록 되어있는데, 이것은 tick range를 어떤 tick 이상, 어떤 tick 미만으로 설정하기 때문에, 1을 빼줌으로써 미만의 범위에 들어가도록 하는 것이다. 이번 테스트케이스에서는 해당하지 않는다.</p><p>이렇게 while문이 끝났다. 왜냐하면 state.sqrtPriceX96과 params.sqrtPriceLimitX96의 값이 같기 때문이다. 이어서 함수를 보자.</p><pre>(self.slot0.sqrtPriceX96, self.slot0.tick) = (state.sqrtPriceX96, state.tick);<br>// update fee growth global<br>if (params.zeroForOne) {<br>    self.feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;<br>} else {<br>    self.feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;<br>}<br><br>unchecked {<br> if (params.zeroForOne == exactInput) {<br>  result = toBalanceDelta(<br>   (params.amountSpecified - state.amountSpeicifiedRemaining).toInt128(),<br>   state.amountCalculated.toInt128()<br>  );<br> } else {<br>  result = toBalanceDelta(<br>   state.amountCalculated.toInt128(),<br>   (params.amountSpecified - state.amountSpecifiedRemaining).toInt128()<br>  );<br> }<br>}</pre><p>먼저 slot0을 업데이트 시켜주고, liquidity와 feeGrowthGlobal 변수를 업데이트 시켜준다. 그리고 result의 값을 업데이트 시켜준다. 먼저 toBalanceDelta에 파라미터 값을 먼저 계산해보자.</p><p>(params.amountSpecified — state.amountSpecifiedRemaining).toInt128()은 1e18 — (1e18 — (3005 + 10)) 이므로 3015가 두번째 인자값으로 넘어간다.</p><p>그리고 amountCalculated은 -2995이다. 첫번째 인자다.</p><p>toBalanceDelta는 전 포스팅에서 다뤘지만 한 번더 보자.</p><pre>function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {<br>    /// @solidity memory-safe-assembly<br>    assembly {<br>        balanceDelta :=<br>            or(shl(128, _amount0), and(0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff, _amount1))<br>    }<br>}</pre><p>amount0은 왼쪽에 amount1값은 오른쪽에 저장하고 있다.</p><p>이제 다시 PoolManager의 swap 함수로 돌아온다.</p><pre>...<br>_accountPoolBalanceDelta(key, delta);<br>//the fee is on the input currency</pre><pre>/// @dev Accumulates a balance change to a map of currency to balance changes<br>function _accountPoolBalanceDelta(PoolKey memory key, BalanceDelta delta) internal {<br>    _accountDelta(key.currency0, delta.amount0());<br>    _accountDelta(key.currency1, delta.amount1());<br>}</pre><pre>function _accountDelta(Currency currency, int128 delta) internal {<br>  if (delta == 0) return;<br><br>  address locker = lockData.getActiveLock();<br>  int256 current = currencyDelta[locker][currency];<br>  int256 next = current + delta;<br><br>  unchecked {<br>      if (next == 0) {<br>          lockData.nonzeroDeltaCount--;<br>      } else if (current == 0) {<br>          lockData.nonzeroDeltaCount++;<br>      }<br>  }<br><br>  currencyDelta[locker][currency] = next;<br>}</pre><p>여기서 locker는 PoolSwapTest 즉 swapRouter가 될 것이다. 그리고 current는 0이다. 그러므로 nonzeroDeltaCount은 2가 증가한다.</p><p>그리고 각각의 currencyDelta[locker]의 currency에 next 값으로 업데이트 시켜준다. 이어서 poolManager의 swap 함수를 보자.</p><pre>unchecked {<br>  if (feeForProtocol &gt; 0) {<br>      protocolFeesAccrued[params.zeroForOne ? key.currency0 : key.currency1] += feeForProtocol;<br>  }<br>  if (feeForHook &gt; 0) {<br>      hookFeesAccrued[address(key.hooks)][params.zeroForOne ? key.currency0 : key.currency1] += feeForHook;<br>  }<br>}<br><br>if (key.hooks.shouldCallAfterSwap()) {<br> if (key.hooks.afterSwap(msg.sender, key, params, delta, hookData) != IHooks.afterSwap.selector) {<br>  revert Hooks.InvalidHookResponse();<br> }<br>}</pre><p>먼저 feeForProtocol과 feeForHook이 없으므로 넘어가자.</p><p>그리고 shouldCallAfterSwap에 해당한다. 바로 afterSwap함수를 호출하고 해당 리턴 값이 afterSwap.selector인지 검사한다.</p><p>바로 훅 컨트랙트의 afterSwap 함수로 가보자.</p><p>LimitOrder.sol의 afterSwap 함수</p><pre>function afterSwap(<br> address,<br> PoolKey calldata key,<br> IPoolManager.SwapParams calldata params,<br> BalanceDelta,<br> bytes calldata<br>) external override poolManagerOnly returns (bytes4) {<br> (int24 tickLower, int24 lower, int24 upper) = _getCrossedTicks(key.toId(), key.tickSpacing);<br> if (lower &gt; upper) return LimitOrder.afterSwap.selector;<br><br> // note that a zeroForOne swap means that the pool is actually gaining token0, so limit order fills are the opposite of swap fills, hence the inversion below<br> bool zeroForOne = !params.zeroForOne;<br> for (; lower &lt;= upper; lower += key.tickSpacing) {<br>  _fillEpoch(key, lower, zeroForOne);<br> }<br><br> setTickLowerLast(key.toId(), tickLower);<br> return LimitOrder.afterSwap.selector;<br>}</pre><p>먼저 poolManagerOnly 모디파이어를 통해서, msg.sender가 poolManager인지 검사한다.</p><p>그리고 _getCrossedTicks 함수를 보자.</p><pre>function _getCrossedTicks(PoolId poolId, int24 tickSpacing) internal view returns (int24 tickLower, int24 lower, int24 upper)<br>{<br> tickLower = getTickLower(getTick(poolId), tickSpacing);<br> int24 tickLowerLast = getTickLowerLast(poolId);<br><br> if (tickLower &lt; tickLowerLast) {<br>  lower = tickLower + tickSpacing;<br>  upper = tickLowerLast;<br> } else {<br>  lower = tickLowerLast;<br>  upper = tickLower - tickSpacing;<br> }<br>}<br><br>function getTickLower(int24 tick, int24 tickSpacing) private pure returns (int24) {<br> int24 compressed = tick/tickSpacing;<br> if (tick &lt; 0 &amp;&amp; tick % tickSpacing != 0) compressed --;<br> return compressed * tickSpacing;<br>}<br><br>function getTickLowerLast(PoolId poolId) public view returns (int24) {<br> return tickLowerLasts[poolId];<br>}</pre><p>getTickLowr 함수는 현재 tick을 tickSpacing의 배수로 만들어주는 함수다. 60이므로 60을 반환한다. 그리고 tickLowerLast는 0이다. 이에 대한 내용은 전 포스팅에서 다뤘다.</p><p>그래서 lower = 0; upper = 60–60 = 0 이다.</p><p>왜 upper가 0이 되냐면, for 문을 보면…</p><p>for (; lower &lt;= upper; lower += key.tickSpacing), 이렇게 가운데 조건에 &lt;가 아닌 ≤ 이므로 한번 반복문을 돌게 되있다.</p><p>그리고 zeroForOne은 true가 된다. 왜냐하면 주석내용에 따르면 swap fill과 limitOrderfill은 반배방향이다. 왜냐하면 원래 false라면, 해당 pool에는 token1이 들어오고, limit order fill을 하게되면 token1이 pool에서 나간다. 그러므로 반대다.</p><p>_fillEpoch(key, lower, zeroForOne) 함수를 호출한다. 인자값으로는 (key, 0, true)가 들어간다. 해당 함수를 보자.</p><pre>function _fillEpoch(PoolKey calldata key, int24 lower, bool zeroForOne) internal {<br> Epoch epoch = getEpoch(key, lower, zeroForOne);<br> if (!epoch.equals(EPOCH_DEFAULT)) {<br>  EpochInfo storage spochInfo = epochInfos[epoch];<br>  <br>  epochInfo.filled = true;<br><br>  (uint256 amount0, uint256 amount1) = abi.decode(<br>   poolManager.lock(<br>    abi.encodeCall(this.lockAcquiredFill, (key, lower, -int256(uint256(epochInfo.liquidityTotal))))<br>   ),<br>   (uint256, uint256)<br>  );<br>  ...</pre><p>여기서 getEpoch를 통해서 가져오는 값은 1이다. 이것은 전 포스팅을 참고하길 바란다.</p><p>EPOCH_DEFAULT는 0이므로, if문 안으로 들어간다. 그리고 epochInfo는 다음과 같다.</p><p>EpochInfos[epochs[keccack256(abi.encode(key,0,true))]] = {</p><p>filled:false,</p><p>currency0,</p><p>currency1,</p><p>token0Total:0,</p><p>token1Total:0,</p><p>liquidityTotal:1000000,</p><p>liquidity[msg.sender]:1000000</p><p>}</p><p>여기에 filled는 true로 바꿔준다. 그리고 poolManager의 lock함수를 호출한다.</p><p>인자로는 해당 컨트랙트의 lockAcquiredFill 함수 selector와, (key, lower:0, -1000000)가 넘겨진다.</p><pre>/// @inheritdoc IPoolManager<br>function lock(bytes calldata data) external override returns (bytes memory result) {<br>    lockData.push(msg.sender);<br><br>    // the caller does everything in this callback, including paying what they owe via calls to settle<br>    result = ILockCallback(msg.sender).lockAcquired(data);<br><br>    if (lockData.length == 1) {<br>        if (lockData.nonzeroDeltaCount != 0) revert CurrencyNotSettled();<br>        delete lockData;<br>    } else {<br>        lockData.pop();<br>    }<br>}</pre><p>그럼 다시 lockData에 limitOrder 컨트랙트 주소가 push된다. 그리고 다시 limitOrder컨트랙트의 lockAcquired함수를 호출한다. 이때 상속하고 있는 BaseHook 컨트랙트의 lockAcquired함수를 호출하게 된다. 그리고 이 함수에서 다시 limitOrder컨트랙트의 lockAcquiredFill함수를 호출하게 된다. 해당 함수를 보자.</p><pre>function lockAcquiredFill(PoolKey calldata key, int24 tickLower, int256 liquidityDelta) external selfOnly returns (uint128 amount0, uint128 amount1)<br>{<br> BalanceDelta delta = poolManager.modifyPosition(<br>  key,<br>  IPoolManager.ModifyPositionParams({<br>   tickLower: tickLower,<br>   tickUpper: tickLower + key.tickSpacing,<br>   liquidityDelta: liquidityDelta<br>  }),<br>  ZERO_BYTES<br> );<br> ...</pre><p>여기서 selfOnly 모디파이어는, msg.sender가 자기 자신인지 검사한다.</p><p>그리고 poolManager의 modifyPosition함수를 보자. 인자값으로 tickLower은 0, tickUpper은 60 그리고 liquidityDelta는 -1000000 이다.</p><pre>/// @inheritdoc IPoolManager<br>function modifyPosition(<br>PoolKey memory key,<br>IPoolManager.ModifyPositionParams memory params,<br>bytes calldata hookData<br>) external override noDelegateCall onlyByLocker returns (BalanceDelta delta) {<br> if (key.hooks.shouldCallBeforeModifyPosition()) {<br>   if (<br>       key.hooks.beforeModifyPosition(msg.sender, key, params, hookData)<br>           != IHooks.beforeModifyPosition.selector<br>   ) {<br>       revert Hooks.InvalidHookResponse();<br>   }<br> }<br> PoolId id = key.toId();<br>  Pool.FeeAmounts memory feeAmounts;<br>  (delta, feeAmounts) = pools[id].modifyPosition(<br>      Pool.ModifyPositionParams({<br>          owner: msg.sender,<br>          tickLower: params.tickLower,<br>          tickUpper: params.tickUpper,<br>          liquidityDelta: params.liquidityDelta.toInt128(),<br>          tickSpacing: key.tickSpacing<br>      })<br>  );<br>...</pre><p>여기서 다시 pools의 modifyPosition함수를 호출한다.</p><pre>function modifyPosition(State storage self, ModifyPositionParams memory params)<br>    internal<br>    returns (BalanceDelta result, FeeAmounts memory fees)<br>{<br> if (self.slot0.sqrtPriceX96 == 0) revert PoolNotInitialized();<br>checkTicks(params.tickLower, params.tickUpper);<br>  uint256 feesOwed0;<br>  uint256 feesOwed1;<br> {<br>    ModifyPositionState memory state;<br>    // if we need to update the ticks, do it<br><br>    if (params.liquidityDelta != 0) {<br>        (state.flippedLower, state.liquidityGrossAfterLower) =<br>            updateTick(self, params.tickLower, params.liquidityDelta, false);<br>        (state.flippedUpper, state.liquidityGrossAfterUpper) =<br>            updateTick(self, params.tickUpper, params.liquidityDelta, true);<br><br>        if (params.liquidityDelta &gt; 0) {<br>            uint128 maxLiquidityPerTick = tickSpacingToMaxLiquidityPerTick(params.tickSpacing);<br>            if (state.liquidityGrossAfterLower &gt; maxLiquidityPerTick) {<br>                revert TickLiquidityOverflow(params.tickLower);<br>            }<br>            if (state.liquidityGrossAfterUpper &gt; maxLiquidityPerTick) {<br>                revert TickLiquidityOverflow(params.tickUpper);<br>            }<br>        }<br><br>        if (state.flippedLower) {<br>            self.tickBitmap.flipTick(params.tickLower, params.tickSpacing);<br>        }<br>        if (state.flippedUpper) {<br>            self.tickBitmap.flipTick(params.tickUpper, params.tickSpacing);<br>        }<br>    }<br><br>    (state.feeGrowthInside0X128, state.feeGrowthInside1X128) =<br>        getFeeGrowthInside(self, params.tickLower, params.tickUpper);<br><br>    (feesOwed0, feesOwed1) = self.positions.get(params.owner, params.tickLower, params.tickUpper).update(<br>        params.liquidityDelta, state.feeGrowthInside0X128, state.feeGrowthInside1X128<br>    );<br><br>    // clear any tick data that is no longer needed<br>    if (params.liquidityDelta &lt; 0) {<br>        if (state.flippedLower) {<br>            clearTick(self, params.tickLower);<br>        }<br>        if (state.flippedUpper) {<br>            clearTick(self, params.tickUpper);<br>        }<br>    }<br>}<br>...이어서</pre><p>전 포스팅에서 해당 함수에 대해서 다뤘으므로, 여기서는 중요한 것만 짚고 넘어 가겠다.</p><p>updateTick함수를 통해서 0과 60 tick은 flip 되어 uninitialized된 상태가 된다. 그리고 0~60 tick range에 feeGrowthInside를 계산하고, position을 업데이트 시킨후에 feesOwed를 계산한다.</p><p>그리고 clearTick함수를 통해서 두개의 틱을 delete 시킨다.</p><p>이어서 modifyPosition 함수를 보자.</p><pre>...<br>if (params.liquidityDelta != 0) {<br>  if (self.slot0.tick &lt; params.tickLower) {<br>      // current tick is below the passed range; liquidity can only become in range by crossing from left to<br>      // right, when we&#39;ll need _more_ currency0 (it&#39;s becoming more valuable) so user must provide it<br>      result = result<br>          + toBalanceDelta(<br>              SqrtPriceMath.getAmount0Delta(<br>                  TickMath.getSqrtRatioAtTick(params.tickLower),<br>                  TickMath.getSqrtRatioAtTick(params.tickUpper),<br>                  params.liquidityDelta<br>              ).toInt128(),<br>              0<br>          );<br>  } else if (self.slot0.tick &lt; params.tickUpper) {<br>      result = result<br>          + toBalanceDelta(<br>              SqrtPriceMath.getAmount0Delta(<br>                  self.slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta<br>              ).toInt128(),<br>              SqrtPriceMath.getAmount1Delta(<br>                  TickMath.getSqrtRatioAtTick(params.tickLower), self.slot0.sqrtPriceX96, params.liquidityDelta<br>              ).toInt128()<br>          );<br><br>      self.liquidity = params.liquidityDelta &lt; 0<br>          ? self.liquidity - uint128(-params.liquidityDelta)<br>          : self.liquidity + uint128(params.liquidityDelta);<br>  } else {<br>      // current tick is above the passed range; liquidity can only become in range by crossing from right to<br>      // left, when we&#39;ll need _more_ currency1 (it&#39;s becoming more valuable) so user must provide it<br>      result = result<br>          + toBalanceDelta(<br>              0,<br>              SqrtPriceMath.getAmount1Delta(<br>                  TickMath.getSqrtRatioAtTick(params.tickLower),<br>                  TickMath.getSqrtRatioAtTick(params.tickUpper),<br>                  params.liquidityDelta<br>              ).toInt128()<br>          );<br>  }<br>}<br>if (params.liquidityDelta &lt; 0 &amp;&amp; self.slot0.hookWithdrawFee &gt; 0) {<br>  // Only take fees if the hook withdraw fee is set and the liquidity is being removed.<br>  fees = _calculateExternalFees(self, result);<br><br>  // Amounts are balances owed to the pool. When negative, they represent the balance a user can take.<br>  // Since protocol and hook fees are extracted on the balance a user can take<br>  // they are owed (added) back to the pool where they are kept to be collected by the fee recipients.<br>  result = result<br>      + toBalanceDelta(<br>          fees.feeForHook0.toInt128() + fees.feeForProtocol0.toInt128(),<br>          fees.feeForHook1.toInt128() + fees.feeForProtocol1.toInt128()<br>      );<br>}<br><br>// Fees earned from LPing are removed from the pool balance.<br>result = result - toBalanceDelta(feesOwed0.toInt128(), feesOwed1.toInt128());<br>}</pre><p>여기서는 맨 마지막 else부분에 해당된다. 왜냐하면 현재 tick이 60이고, 현재 tickRange가 0~60이다.</p><p>그래서 amount0은 0이되고, amount1은 getAmount1Delta함수를 통해 구해진다. -3004가 된다.</p><p>그리고 마지막 if문은 hookWithdrawFee이 없으므로 해당되지 않는다. 그러므로 return되는 fees값은 0이다.</p><p>그리고 마지막에 feesOwed를 반영시킨다. 이때 feesOwed1이 9여서, 결국 amount0은 0, amount1은 -3013이 된다.</p><p>그 다음에 다시 PoolManager컨트랙트의 modifyPosition함수를 보자.</p><pre>...<br>_accountPoolBalanceDelta(key, delta);<br><br>...생략<br><br>/// @dev Accumulates a balance change to a map of currency to balance changes<br>function _accountPoolBalanceDelta(PoolKey memory key, BalanceDelta delta) internal {<br>    _accountDelta(key.currency0, delta.amount0());<br>    _accountDelta(key.currency1, delta.amount1());<br>}<br>...<br>function _accountDelta(Currency currency, int128 delta) internal {<br>  if (delta == 0) return;<br><br>  address locker = lockData.getActiveLock();<br>  int256 current = currencyDelta[locker][currency];<br>  int256 next = current + delta;<br><br>  unchecked {<br>      if (next == 0) {<br>          lockData.nonzeroDeltaCount--;<br>      } else if (current == 0) {<br>          lockData.nonzeroDeltaCount++;<br>      }<br>  }<br><br>  currencyDelta[locker][currency] = next;<br>}</pre><p>여기서 locker는 limitOrder 훅 컨트랙트다. 그러므로 아까 업데이트된 값하고 상관없다.</p><p>그래서 nonzeroDeltaCount는 1이 증가하고, currencyDelta[locker][token1]은 -3013이 된다.</p><p>그리고 LimitOrder.sol의 lockAcquiredFill함수로 돌아간다.</p><pre>...<br> if (delta.amount0() &lt;0) poolManager.mint(key.currency0, address(this), amount0 = uint128(-delta.amount0()));<br> if (delta.amount1() &lt;0) poolManager.mint(key.currency1, address(this), amount1 = uint128(-delta.amount1()));</pre><p>첫번째 if는 amount0가 0이므로 무시된다. 그리고 두번째는 -3013이므로 poolManager컨트랙트의 mint함수를 호출한다. 그리고 3013값을 인자로 넘겨준다.</p><pre>/// @inheritdoc IPoolManager<br>    function mint(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>        _accountDelta(currency, amount.toInt128());<br>        _mint(to, currency.toId(), amount, &quot;&quot;);<br>    }</pre><p>먼저 _accountDelta함수를 통해서 방금전에 업데이트 시킨 nonzeroDeltaCount를 1 감소시키고, currencyDelta[locker][token1]을 0으로 업데이트 시킨다.</p><p>그리고 _mint는 ERC1155이다. 이에 대해서는 다음 포스팅에서 다루도록 하겠다. 여기는 그냥 to는 limitOrder 컨트랙트이고, currency는 token0 그리고 amount는 3013이다.</p><p>그리고 LimitOrder.sol의 _fillEpoch함수로 돌아간다.</p><pre> unchecked {<br>  epochInfo.token0Total += amount0;<br>  epochInfo.token1Total += amount1;<br> }<br> setEpoch(key, lower, zeroForOne, EPOCH_DEFAULT);<br> emit Fill(epoch, key, lower, zeroForOne);<br>}<br>...<br>function setEpoch(PoolKey memory key, int24 tickLower, bool zeroForOne, Epoch epoch) private {<br>      epochs[keccak256(abi.encode(key, tickLower, zeroForOne))] = epoch;<br>  }</pre><p>이제 epochInfo의 filled는 true이고 token1Total은 3013이 되었다.</p><p>setEpoch함수를 호출한다. 이때 인자는 (key, 0, true)다.</p><p>그리고 다시 LimitOrder.sol의 afterSwap함수다.</p><pre>...<br> setTickLowerLast(key.toId(), tickLower);<br> return LimitOrder.afterSwap.selector;<br>}<br>...<br>function setTickLowerLast(PoolId poolId, int24 tickLower) private {<br>        tickLowerLasts[poolId] = tickLower;<br>    }</pre><p>여기서 tickLower: 60을 인자로 넣고 tickLowerLast를 60으로 업데이트 시켜준다.</p><p>그리고 poolManager컨트랙트의 swap 함수에서 Swap 이벤트를 emit하고 해당함수는 끝난다.</p><p>그리고 이제 맨 처음, swapRouter인 PoolSwapTest.sol의 lockAcquired함수로 돌아간다.</p><pre>...<br>BalanceDelta delta = manager.swap(data.key, data.params, new bytes(0));<br><br>if (data.params.zeroForOne) { //false<br> ...생략<br>} else {<br> if (delta.amount1() &gt; 0) { //3015 true<br>  if (data.testSettings.settleUsingTransfer) { //true<br>   if (data.key.currency1.isNative()) { //false<br>    manager.settle{value: uint128(delta.amount1())}(data.key.currency1);<br>   } else { //true<br>    IERC20Minimal(Currency.unwrap(data.key.currency1)).transferFrom(<br>     data.sender, address(manager), uint128(delta.amount1())<br>    );<br>    manager.settle(data.key.currency1);<br>   }<br>  } else { //false<br>   manager.safeTransferFrom(<br>    data.sender,<br>    address(manager),<br>    uint256(uint160(Currency.unwrap(data.key.currency1))),<br>    uint128(delta.amount1()),<br>    &quot;&quot;<br>   );<br>  }<br> }<br> if (delta.amount0() &lt;0 ) { //true<br>  if (data.testSettings.withdrawTokens) { //true<br>   manager.take(data.key.currency0, data.sender, uint128(-delta.amount0()));<br>  } else {<br>   manager.mint(data.key.currency0, data.sender, uint128(-delta.amount0()));<br>  }<br> }<br>}<br>return abi.encode(delta);</pre><p>여기서 delta값은 amount0은 -2995 그리고 amount1은 3015다.</p><p>그리고 3015만큼 poolManager컨트랙트에게 transfer한다. 그리고 manager 컨트랙트의 settle함수를 호출한다.</p><pre>/// @inheritdoc IPoolManager<br>function settle(Currency currency) external payable override noDelegateCall onlyByLocker returns (uint256 paid) {<br>    uint256 reservesBefore = reservesOf[currency];<br>    reservesOf[currency] = currency.balanceOfSelf();<br>    paid = reservesOf[currency] - reservesBefore;<br>    // subtraction must be safe<br>    _accountDelta(currency, -(paid.toInt128()));<br>}</pre><p>여기에 reservesBefore는 0이다. 그리고 balanceOfSelf()는 3015를 반환한다. 그리고 이값을 reservesOf 변수에 업데이트 시킨다.</p><p>paid는 3015가 되고, _accountDelta에 -3015를 인자로 넘긴다. 아까 locker가 swapRouter(=PoolSwapTest)였던 currencyDelta의 값은 3015였다. 그러므로 0이된다.</p><p>그리고 PoolSwapTest에서 manager컨틀개트의 take함수를 호출한다. 인자로는 (currency0, sender address, 2995)를 넘겨준다.</p><pre>function take(Currency currency, address to, uint256 amount) external override noDelegateCall onlyByLocker {<br>    _accountDelta(currency, amount.toInt128());<br>    reservesOf[currency] -= amount;<br>    currency.transfer(to, amount);<br>}</pre><p>여기서 locker가 swapRouter(=PoolSwapTest)였던 currencyDelta의 값은 2995였다. 그러므로 0이된다.</p><p>여기서 기존의 reservesOf[token0]은 2996이었다. 전 포스팅을 참고바란다. 여기서 2995를 빼면 1이다. (오차가 생기는 것 같다..). 그리고 swap을 하는 address로 해당 amount만큼 transfer한다.</p><p>이렇게 swap 함수는 끝나게 된다. 그럼 지정가 주문을 넣은 분은 limitOrder컨트랙트의 withdraw함수를 통해서 처음에 넣었던 token0이 아닌 token1로 withdraw 할 수 있다.</p><p>limitOrder.sol의 withdraw함수를 보자.</p><pre>function withdraw(Epoch epoch, address to) external returns (uint256 amount0, uint256 amount1) {<br>    EpochInfo storage epochInfo = epochInfos[epoch];<br>    if (!epochInfo.filled) revert NotFilled();<br><br>    uint128 liquidity = epochInfo.liquidity[msg.sender];<br>    if (liquidity == 0) revert ZeroLiquidity();<br>    delete epochInfo.liquidity[msg.sender];<br><br>    uint256 token0Total = epochInfo.token0Total;<br>    uint256 token1Total = epochInfo.token1Total;<br>    uint128 liquidityTotal = epochInfo.liquidityTotal;<br><br>    amount0 = FullMath.mulDiv(token0Total, liquidity, liquidityTotal);<br>    amount1 = FullMath.mulDiv(token1Total, liquidity, liquidityTotal);<br><br>    epochInfo.token0Total = token0Total - amount0;<br>    epochInfo.token1Total = token1Total - amount1;<br>    epochInfo.liquidityTotal = liquidityTotal - liquidity;<br><br>    poolManager.lock(<br>        abi.encodeCall(this.lockAcquiredWithdraw, (epochInfo.currency0, epochInfo.currency1, amount0, amount1, to))<br>    );<br><br>    emit Withdraw(msg.sender, epoch, liquidity);<br>}</pre><p>해당 코드를 보면, withdraw하는 자의 liquidity를 불러오고, 해당 liquidity를 liquidityTotal로 나눈 만큼을 tokenTotal과 곱해서 그만큼을 withdraw하게 된다. 그리고 epochInfo변수를 업데이트 시킨다.</p><p>그리고 manager컨트랙트의 lock함수를 호출하고, 다시 이 컨트랙트의 lockAcquireWithdraw함수가 호출된다. lock하는 과정은 앞에서 많이 다뤘으므로 여기서는 생략하겠다.</p><pre>function lockAcquiredWithdraw(<br>    Currency currency0,<br>    Currency currency1,<br>    uint256 token0Amount,<br>    uint256 token1Amount,<br>    address to<br>) external selfOnly {<br>    if (token0Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency0))), token0Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency0, to, token0Amount);<br>    }<br>    if (token1Amount &gt; 0) {<br>        poolManager.safeTransferFrom(<br>            address(this), address(poolManager), uint256(uint160(Currency.unwrap(currency1))), token1Amount, &quot;&quot;<br>        );<br>        poolManager.take(currency1, to, token1Amount);<br>    }<br>}</pre><p>여기서 token0Amount은 0 이고 token1Amount은 3013이다.</p><p>그리고 poolManager컨트랙트의 safeTransferFrom함수를 호출한다. erc1155의 함수다. 아까 mint함수에서 limitOrder컨트랙트로 3013만큼 erc1155를 mint했었다. 그것을 poolManager컨트랙트로 transfer하는 것이다.</p><p>그러면, poolManager컨트랙트의 onERC1155Received 함수가 호출된다.</p><pre>function _burnAndAccount(Currency currency, uint256 amount) internal {<br>    _burn(address(this), currency.toId(), amount);<br>    _accountDelta(currency, -(amount.toInt128()));<br>}<br><br>function onERC1155Received(address, address, uint256 id, uint256 value, bytes calldata) external returns (bytes4) {<br>    if (msg.sender != address(this)) revert NotPoolManagerToken();<br>    _burnAndAccount(CurrencyLibrary.fromId(id), value);<br>    return IERC1155Receiver.onERC1155Received.selector;<br>}</pre><p>여기서 받은 erc1155를 burn시키고, _accountDelta함수를 통해서 locker는 limitOrder로 currencyDelta[locker][currency] 에 -3013으로 대입하고, nonzeroDeltaCount는 1이 증가한다.</p><p>그리고 다시 lockAcquiredWithraw함수에서 poolManager.take 함수를 호출한다. 아까 다뤄서 코드는 생략하겠다. locker는 limitOrder로 currencyDelta[locker][currency] 에 0을 대입하고, nonzeroDeltaCount는 1을 감소시킨다. 그리고 reservesOf[currency]는 3015였는데 3013을 감소시켜 2가 남는다(오차가 생긴다). 그리고 3013을 to(지정가 주문을 한 address)로 transfer하고 끝나게 된다.</p><p>이렇게 3개의 시리즈로 limitOrder훅에 대해서 다뤄봤다. 하지만 코드가 너무 길고 내용이 너무 길다. 따라서 3개의 편을 정리하고 일러스트도 포함해서 이해하기 쉽게 하나의 포스팅으로 다시 올려야겠다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4908e264169d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>