レッスン7 — 値段を自分で決める: beforeSwapReturnDelta
出典: Uniswap/v4-core
v4.0.0、fabrknt/shadowbook7ae1dd1。Shadowbook はここから
7d07439(レッスン1〜6)ではなく、今のmainである7ae1dd1を読む。2 つの違いはtest/DirectionalFee.t.solの fuzz の範囲だけで(レッスン6)、src/、script/、README.md、test/Shadowbook.t.solは同じだ。これまでに引いた Shadowbook の行はそのまま成り立つ。Shadowbook がビルドに使う v4-core は59d3ecf(v4-peripheryc6e4754の中)。そこでもBeforeSwapDelta.sol、Pool.sol、Currency.solは同じで、Hooks.sol、PoolManager.sol、IHooks.solの違いは swap と流動性のパラメータ構造体の置き場所だけだ。そのためHooks.solは 1 行下にずれる。以下の v4-core の行は v4.0.0 で引く。読了目安:約 25 分(手を動かすと 45 分)
曲線は何も swap しない。swap は丸ごと hook が約定させる
hook のアドレスに BEFORE_SWAP_RETURNS_DELTA のビットがあれば、beforeSwap は BeforeSwapDelta を返せる。
符号つきの 2 つの量だ。1 つは swap する人が指定した通貨、もう 1 つはもう片方の通貨のもの。
PoolManager は 1 つ目の分だけ、曲線が swap する量を減らす。両方を hook の勘定につけ、その逆を swap する人の勘定につける。
では、swap の量とちょうど同じだけ返したらどうなるか。
曲線にやることが残らない。hook が swap を丸ごと引き受け、値段を自分で決めたことになる。
Shadowbook はすべての swap でこれをやっている。
keeper が出す気配から値段を出す。入ってくる側を ERC-6909 の claim として受け取り、出ていく側を自分の在庫から払い、自分の勘定をゼロに戻す delta を返す。
このレッスンでは、その流れを v4-core と Shadowbook で読み、それから 3 通りに壊す。
beforeSwapが返した delta をPoolManagerがどう使うか。swap の量と同じ delta で曲線が飛ばされる理由BeforeSwapDelta: どちらの通貨が「指定された側(specified)」か、符号の決まり- v4-core 自身のテスト用 hook にある型と、Shadowbook がそこから違う点
- Shadowbook が swap に値段をつけ、端数を丸め、
PoolManagerと自分の側を精算する方法 - 符号の間違い、払い忘れ、逆向きの丸めが、それぞれどう見えるか
delta は、swap のどこに入るのか
PoolManager.swap はまず hook を呼ぶ。それから残りを swap し、2 つの delta を勘定につける(PoolManager.sol L196-L224、一部省略)。
BeforeSwapDelta beforeSwapDelta;
{
int256 amountToSwap;
uint24 lpFeeOverride;
(amountToSwap, beforeSwapDelta, lpFeeOverride) = key.hooks.beforeSwap(key, params, hookData);
...
}
BalanceDelta hookDelta;
(swapDelta, hookDelta) = key.hooks.afterSwap(key, params, swapDelta, hookData, beforeSwapDelta);
// if the hook doesn't have the flag to be able to return deltas, hookDelta will always be 0
if (hookDelta != BalanceDeltaLibrary.ZERO_DELTA) _accountPoolBalanceDelta(key, hookDelta, address(key.hooks));
_accountPoolBalanceDelta(key, swapDelta, msg.sender);
曲線が受け取るのは、swap する人の量ではなく amountToSwap だ。
これを計算するのは Hooks.beforeSwap。hook の delta を読むのは、アドレスにビットがあるときだけだ(libraries/Hooks.sol L264-L279)。
// skip this logic for the case where the hook return is 0
if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());
// any return in unspecified is passed to the afterSwap hook for handling
int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();
// Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
if (hookDeltaSpecified != 0) {
bool exactInput = amountToSwap < 0;
amountToSwap += hookDeltaSpecified;
if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
HookDeltaExceedsSwapAmount.selector.revertWith();
}
}
}
入る量を指定する swap(exact input)の amountSpecified は負だ(レッスン2)。
hook が指定側の delta として +|amountSpecified| を返すと、amountToSwap は 0 になる。するとプールの swap は、ゼロの delta を返してすぐに戻る(libraries/Pool.sol L320)。
if (params.amountSpecified == 0) return (BalanceDeltaLibrary.ZERO_DELTA, 0, swapFee, result);
「swap より多く返したら?」と思うかもしれない。
swap より大きい delta は exact input を exact output に変えてしまう。だから HookDeltaExceedsSwapAmount で revert する。
続いて Hooks.afterSwap が 2 つの数を token0 と token1 に直し、swap する人から hook へ付け替える(L304-L313)。
BalanceDelta hookDelta;
if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
: toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);
// the caller has to pay for (or receive) the hook's delta
swapDelta = swapDelta - hookDelta;
}
return (swapDelta, hookDelta);
BeforeSwapDelta: 1 つの語に 2 つの数
この型は 2 つの int128 を 1 つの int256 に詰める(types/BeforeSwapDelta.sol L4-L16)。
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
では、「指定された側」とはどちらか。
amountSpecified の通貨のことだ。上の afterSwap の条件から、こうなる。
zeroForOne(token0 を売る) | !zeroForOne(token0 を買う) | |
|---|---|---|
exact input(amountSpecified < 0) | 指定側 = token0、入る側 | 指定側 = token1、入る側 |
exact output(amountSpecified > 0) | 指定側 = token1、出る側 | 指定側 = token0、出る側 |
符号は hook から見たもので、ほかのすべての delta と同じ決まりだ: "Positive: the hook is owed/took currency, negative: the hook owes/sent currency"(interfaces/IHooks.sol L101)。
正なら hook が受け取る(受け取った)、負なら hook が払う(払った)。
swap する人には、その逆がつく。
v4-core にある型: 1:1 の曲線
v4-core には、曲線を直線に置き換えるテスト用の hook が入っている(src/test/CustomCurveHook.sol L40-L47)。
// this "custom curve" is a line, 1-1
// take the full input amount, and give the full output amount
manager.take(inputCurrency, address(this), amount);
outputCurrency.settle(manager, address(this), amount, false);
// return -amountSpecified as specified to no-op the concentrated liquidity swap
BeforeSwapDelta hookDelta = toBeforeSwapDelta(int128(-params.amountSpecified), int128(params.amountSpecified));
return (IHooks.beforeSwap.selector, hookDelta, 0);
この種の hook は、どれも 3 段でできている。
- 入る側を受け取る
- 出る側を払う
- 自分の勘定で両方を打ち消す delta を返す
a を入れる exact input の swap で見てみる。
takeで、hook の入る側は−aになる。settleで、出る側は+aになる。- 返した delta(指定側
+a、もう片方−a)で、両方ゼロに戻る。
swap する人には入る側 −a、出る側 +a が残る。レッスン2 のとおり、ルーターがそれを払い、受け取る。
Shadowbook の beforeSwap: 同じ 3 段を、自分の値段で
Shadowbook も同じ 3 段を、自分の値段でやっている(src/Shadowbook.sol L232-L265)。
function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
external
onlyPoolManager
returns (bytes4, BeforeSwapDelta, uint24)
{
if (PoolId.unwrap(key.toId()) != PoolId.unwrap(poolId)) revert WrongPool();
if (paused) revert Paused();
Quote memory q = quote;
if (q.updatedAt == 0) revert NoQuote();
if (block.timestamp - q.updatedAt > maxAge) revert StaleQuote(block.timestamp - q.updatedAt);
if (q.mid < minMid || q.mid > maxMid) revert OutOfBand(q.mid);
if ((params.zeroForOne ? q.bidBps : q.askBps) == CLOSED) revert SideClosed(params.zeroForOne);
bool exactInput = params.amountSpecified < 0;
uint256 specified = exactInput ? uint256(-params.amountSpecified) : uint256(params.amountSpecified);
uint256 unspecified = _price(params.zeroForOne, exactInput, specified, q);
(uint256 amountIn, uint256 amountOut) = exactInput ? (specified, unspecified) : (unspecified, specified);
if (amountOut == 0) revert ZeroOutput();
(Currency cin, Currency cout) =
params.zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
uint256 notional1 = params.zeroForOne ? amountOut : amountIn;
budget.spend(notional1, notionalCap, capWindow);
poolManager.mint(address(this), cin.toId(), amountIn);
_payOut(cout, amountOut);
emit Filled(params.zeroForOne, amountIn, amountOut, notional1);
BeforeSwapDelta d = exactInput
? toBeforeSwapDelta(int128(int256(specified)), -int128(int256(unspecified)))
: toBeforeSwapDelta(-int128(int256(specified)), int128(int256(unspecified)));
return (IHooks.beforeSwap.selector, d, 0);
}
4 つに分けて読む。
1. 断る。
対象のプールであること。止まっていないこと。気配があり、maxAge より古くなく、中値が owner の決めた幅に収まり、求められた側が開いていること。
どれも revert なので、断られた swap は起きない。これらはレッスン8 でもう一度扱う。
2. 値段。
swap する人が指定しなかった側の量を、_price が出す(後述)。
3. 自分の側の精算。
入る側について、自分宛てに ERC-6909 の claim を mint する(勘定は −amountIn、レッスン2)。そして出る側を払う(+amountOut)。
「v4-core のテスト用 hook のように、入る側を take すればいいのでは?」
理由はコントラクトのコメントにある(L31-L33): "A swap's input arrives as claims (the swapper settles after the hook returns, so the manager holds no real tokens yet); its output burns claims first and pays the rest from real balances."
swap する人が払うのは hook が戻ったあとなので、その時点の manager には本物のトークンがまだない、ということだ。
4. delta。
- exact input なら
+specified(受け取るべき入る側)と−unspecified(払うべき出る側)。 - exact output なら
−specified(出る側)と+unspecified(入る側)。
どちらも上の表どおりの符号だ。
手数料は 0。Shadowbook のキーの手数料は 0 で、曲線は一度も動かないからだ(README L205-L207)。hook の稼ぎはスプレッドだ。
出る側の支払いはこうなっている(L285-L300)。
function _payOut(Currency c, uint256 amount) internal {
uint256 claims = poolManager.balanceOf(address(this), c.toId());
uint256 burnAmt = claims < amount ? claims : amount;
if (burnAmt != 0) poolManager.burn(address(this), c.toId(), burnAmt);
if (amount > burnAmt) _settle(c, amount - burnAmt);
}
function _settle(Currency c, uint256 amount) internal {
if (c.isAddressZero()) {
poolManager.settle{value: amount}();
} else {
poolManager.sync(c);
c.transfer(address(poolManager), amount);
poolManager.settle();
}
}
先に、前の swap でたまった claim を燃やす(燃やすと hook の勘定にプラスがつく)。足りない分は、本物のトークンで sync、送金、settle の順に払う。
つまり hook の在庫は 2 種類ある。自分が持つトークンと、PoolManager の中の claim だ。
inventory(currency) はその合計を返す(L205-L208)。owner は redeem で claim をトークンに戻す。redeem は自分で unlock を呼ぶ(L193-L203)。
token0 を 1 つ、71.964 token1 の bid で売る exact input の swap を考える。PoolManager の中の hook の勘定は、こう動く。
| 段 | token0 | token1 |
|---|---|---|
入る側の claim を mint | −1e18 | |
_payOut: sync、送金、settle | +71,964,000 | |
| 返す delta: 指定側 +1e18、もう片方 −71,964,000 | +1e18 | −71,964,000 |
| swap 後の hook | 0 | 0 |
曲線からの swapDelta は 0 だ。だから swap する人には、swapDelta − hookDelta で token0 が −1e18、token1 が +71,964,000 残る。
ルーターはそれを払い、受け取る。そのあとで unlock が、すべての delta がゼロかを確かめる。
値段は、どちらに丸めるのか
気配は、中値と、片側ごとの中値からの距離だ。
値段は、token0 の最小単位あたりの token1 の最小単位に PRICE_SCALE(1e36)を掛けた数(L21-L25、L39)。
_price はこうだ(L267-L283)。
/// The unspecified side of a swap at the quoted bid (user sells token0) or ask (user buys
/// token0). Rounding always favours the hook.
function _price(bool zeroForOne, bool exactInput, uint256 amount, Quote memory q) internal pure returns (uint256) {
uint256 px = zeroForOne
? uint256(q.mid) * (BPS - q.bidBps) / BPS // bid
: FullMath.mulDivRoundingUp(q.mid, BPS + q.askBps, BPS); // ask
if (zeroForOne) {
// in: token0, out: token1
return exactInput
? FullMath.mulDiv(amount, px, PRICE_SCALE) // out1
: FullMath.mulDivRoundingUp(amount, PRICE_SCALE, px); // in0
}
// in: token1, out: token0
return exactInput
? FullMath.mulDiv(amount, PRICE_SCALE, px) // out0
: FullMath.mulDivRoundingUp(amount, px, PRICE_SCALE); // in1
}
| swap する人 | hook が計算するもの | 丸め |
|---|---|---|
| token0 を売る、exact input | 出る token1 = 入る量 × bid | 切り捨て |
| token0 を売る、exact output | 入る token0 = 出る量 ÷ bid | 切り上げ |
| token0 を買う、exact input | 出る token0 = 入る量 ÷ ask | 切り捨て |
| token0 を買う、exact output | 入る token1 = 出る量 × ask | 切り上げ |
bid 自体は切り捨て、ask は切り上げ。
丸めはすべて、swap する人に不利な向きだ。だから、どんなに小さな swap でも気配よりよい値段にはならない。
テストは中値 72e24(小数 18 桁のトークン 1 つが 72 USDC)、片側 5 bp で数字を固定している(test/Shadowbook.t.sol L91-L124)。
- 1e18 を売れば 71,964,000。
- 1e18 を買えば 72,036,000。
どんな量とスプレッドでもこの不等式が成り立つことを、fuzz テストが確かめる(L126-L149): "Whatever the size, the hook never pays out more than the quoted price allows."
曲線を飛ばすと、何が変わるのか
Swap イベントはゼロを示す。
イベントが運ぶのは曲線の delta で、それは 0 だ。量は hook 自身の Filled イベントにある(L69)。
Swap イベントだけで出来高を数える仕組みには、ここの取引は見えない(演習で両方を見る)。
価格の上限が効かない。
README の言葉では(L132-L134): "Swaps fill entirely in beforeSwap, so the PoolManager's concentrated-liquidity step gets zero and the swapper's sqrtPriceLimitX96 has no effect. Callers must protect themselves with a minimum output (exact input) or maximum input (exact output), as aggregators already do."
自分の身は、受け取る量の下限か、払う量の上限で守る必要がある。
外からの流動性はない。
Shadowbook の beforeAddLiquidity は、必ず NoExternalLiquidity で revert する(レッスン4)。
そもそも hook がすべての swap を丸ごと引き受けるので、曲線にポジションを足しても取引されることはない。
何が起こりうるか
| 間違い | 起きること | どこに出るか |
|---|---|---|
| delta の符号が逆 | 曲線に 2 倍の量の swap が回り、swap する人の delta が逆を向く | ルーター自身の検査、または CurrencyNotSettled(演習 B) |
| 出る側を払っていない | hook の勘定がマイナスのまま残る | CurrencyNotSettled。PoolManager が swap する人に払えなければ、その手前(演習 A) |
| swap する人に有利な丸め | 約定ごとに最小単位 1 つまでを渡してしまう | 不等式を確かめるテストだけ(演習 C) |
| swap より大きい指定側の delta | swap の種類が変わってしまう | HookDeltaExceedsSwapAmount |
アドレスに BEFORE_SWAP_RETURNS_DELTA がない | PoolManager は delta を読まない(上の hasPermission) | Shadowbook のコンストラクタはそのアドレスを拒む(レッスン3) |
演習: 約定を読み、3 通りに壊す
このレッスンが引くコミットで、Shadowbook を新しく clone する。
git clone https://github.com/fabrknt/shadowbook shadowbook-7ae1dd1
cd shadowbook-7ae1dd1
git checkout 7ae1dd1
forge install
forge test
出力はこうだった(forge 1.7.1、macOS、2026-11-14。テストごとの行は省いた)。
Compiling 88 files with Solc 0.8.26
Ran 21 tests for test/DirectionalFee.t.sol:DirectionalFeeTest
Suite result: ok. 21 passed; 0 failed; 0 skipped; …
Ran 28 tests for test/Shadowbook.t.sol:ShadowbookTest
Suite result: ok. 28 passed; 0 failed; 0 skipped; …
Ran 2 test suites in …: 49 tests passed, 0 failed, 0 skipped (49 total tests)
(注:forge install は foundry.lock を末尾の改行なしで書き直すので、git status には変更ありと出る。害はない。)
約定を読む。
exact input の売りを完全なトレースつきで走らせ、大事な呼び出しだけを残す。
forge test --mt test_sellToken0_exactIn_atBid -vvvv | grep -E "::beforeSwap|::mint|::sync|::transfer|::settle\(|::take|emit Filled|emit Swap|Return\] 0x575e24b4"
出力はこうだ。長い引数は … で切った。
│ │ │ │ ├─ [150243] 0x4444000000000000000000000000000000002888::beforeSwap(PoolSwapTest: […], PoolKey({ … }), SwapParams({ zeroForOne: true, amountSpecified: -1000000000000000000 [-1e18], … }), 0x)
│ │ │ │ │ ├─ [25484] PoolManager::mint(0x4444000000000000000000000000000000002888, 124512733235148509670984850249661524172173354937 [1.245e47], 1000000000000000000 [1e18])
│ │ │ │ │ ├─ [2497] PoolManager::sync(MockERC20: [0x212224D2F2d262cd093eE13240ca4873fcCBbA3C])
│ │ │ │ │ ├─ [26329] MockERC20::transfer(PoolManager: […], 71964000 [7.196e7])
│ │ │ │ │ ├─ [4036] PoolManager::settle()
│ │ │ │ │ ├─ emit Filled(zeroForOne: true, amountIn: 1000000000000000000 [1e18], amountOut: 71964000 [7.196e7], notional1: 71964000 [7.196e7])
│ │ │ │ │ └─ ← [Return] 0x575e24b4, 340282366920938463803656974352706674919374607431696247456 [3.402e56], 0
│ │ │ │ ├─ emit Swap(id: 0x7d5d05…, sender: PoolSwapTest: […], amount0: 0, amount1: 0, sqrtPriceX96: 79228162514264337593543950336 [7.922e28], liquidity: 0, tick: 0, fee: 0)
│ │ │ ├─ [2497] PoolManager::sync(MockERC20: [0x15cF58144EF33af1e14b5208015d11F9143E27b9])
│ │ │ ├─ [28836] MockERC20::transferFrom(ShadowbookTest: […], PoolManager: […], 1000000000000000000 [1e18])
│ │ │ ├─ [4024] PoolManager::settle()
│ │ │ ├─ [9062] PoolManager::take(MockERC20: [0x212224D2F2d262cd093eE13240ca4873fcCBbA3C], ShadowbookTest: […], 71964000 [7.196e7])
│ │ │ │ ├─ [6429] MockERC20::transfer(ShadowbookTest: […], 71964000 [7.196e7])
コードと照らして読む。
beforeSwapの中で、token0 の claim 1e18 のmint(id はトークンのアドレスを数にしたもの)。次に token1 71,964,000 のsync・送金・settle、そしてFilled。| grepなしの完全なトレースを見ると、このsyncの時点でPoolManagerの token1 は 0 だったことも分かる。このテストのPoolManagerには、ほかのプールのトークンがない。- 2 つ目の戻り値は、
BeforeSwapDeltaを 1 つの数で表したものだ。分けてみる:python3 -c "v=340282366920938463803656974352706674919374607431696247456; lo=v&(2**128-1); print(v>>128, lo-2**128 if lo>=2**127 else lo)"は1000000000000000000 -71964000を出す。指定側 +1e18、もう片方 −71,964,000 だ。 Swapにはamount0: 0, amount1: 0, liquidity: 0, fee: 0と記録される。曲線は何もしていない。量はFilledにある。- hook が戻ってから、ルーター(
PoolSwapTest)が token0 1e18 を払い(sync、transferFrom、settle)、token1 71,964,000 を受け取る。コントラクトのコメントのとおり、swap する人が払うのは hook が戻ったあとだ。
では、作業用のコピーで壊す。各段とも新しいコピーから始める。
# from the directory that holds shadowbook-7ae1dd1
rm -rf /tmp/shadowbook-scratch
cp -R shadowbook-7ae1dd1 /tmp/shadowbook-scratch && cd /tmp/shadowbook-scratch
rm -rf cache/fuzz # no fuzz failures replayed from earlier runs
A. 出る側を払わない。
258 行目の _payOut(cout, amountOut); をコメントアウトする。
sed -i '' '258s|^ _payOut| // _payOut|' src/Shadowbook.sol # GNU sed: sed -i without ''
forge test --mt test_sellToken0_exactIn_atBid
[FAIL: WrappedError(0x212224D2F2d262cd093eE13240ca4873fcCBbA3C, 0xa9059cbb, 0x4e487b710000000000000000000000000000000000000000000000000000000000000011, 0xf27f64e4)] test_sellToken0_exactIn_atBid() (gas: 275334)
CurrencyNotSettled が出ると思うかもしれない。だが、unlock が何かを確かめる前に失敗している。
ルーターの take が、誰も払い込んでいない token1 71,964,000 を送るよう PoolManager に求めた。トークンの transfer(0xa9059cbb)がアンダーフロー(0x4e487b71…11 は Panic(0x11))を起こした。v4-core はそれを ERC20TransferFailed(0xf27f64e4、types/Currency.sol L81-L85)で包む。
本番の PoolManager は、受け持つすべてのプールのトークンを持っている。だから本番では take が通ることがある。
それを再現する。編集はそのままにして、test/Shadowbook.t.sol の test_sellToken0_exactIn_atBid の先頭に 1 行足す。
function test_sellToken0_exactIn_atBid() public {
MockERC20(Currency.unwrap(currency1)).transfer(address(manager), 100e6); // the manager holds other pools' USDC
[FAIL: CurrencyNotSettled()] test_sellToken0_exactIn_atBid() (gas: 308901)
今度は、swap する人にほかのプールのトークンから払われた。ルーターのコールバックが戻った時点で hook の −71,964,000 が残っているので、unlock が revert する。
git checkout -- src test で戻す(足した 1 行だけなら、テストは通る)。
B. 符号を逆にする。
262 行目で、マイナス記号を 2 つ目の引数から 1 つ目に移す。
sed -i '' '262s|toBeforeSwapDelta(int128(int256(specified)), -int128(int256(unspecified)))|toBeforeSwapDelta(-int128(int256(specified)), int128(int256(unspecified)))|' src/Shadowbook.sol
forge test --mt test_sellToken0_exactIn_atBid -vvv | grep -E "FAIL|emit Swap"
[FAIL: deltaAfter1 is not greater than or equal to 0] test_sellToken0_exactIn_atBid() (gas: 671433)
│ │ │ │ ├─ emit Swap(id: 0x7d5d05…, sender: PoolSwapTest: […], amount0: 0, amount1: 0, sqrtPriceX96: 4295128740 [4.295e9], liquidity: 0, tick: -887272 [-8.872e5], fee: 0)
指定側の delta が −1e18 なので、amountToSwap は −2e18 になった。exact input のままなので、v4-core は通す。
曲線は流動性ゼロに対して swap した。プールの価格を swap する人の上限(sqrtPriceX96: 4295128740、tick: -887272)まで動かして、何も約定させなかった。
swap する人の token1 の delta は、売りとは逆のマイナスになった。それをテスト用ルーター自身の検査(PoolSwapTest.sol L64-L72、Shadowbook がビルドに使う v4-core のもの)が止めた。
「その検査がなかったら?」
上の表で数えると、hook 自身の勘定は token0 −2e18、token1 +143,928,000 でずれたままだ。だから unlock が CurrencyNotSettled で revert する。
どちらにしても、エラーが名指しするのはルーターかロックで、hook ではない。
git checkout -- src で戻す。
C. 逆向きに丸める。
exact output の売りで、入る量を切り捨てにする(277 行目)。
sed -i '' '277s|FullMath.mulDivRoundingUp(amount, PRICE_SCALE, px)|FullMath.mulDiv(amount, PRICE_SCALE, px)|' src/Shadowbook.sol
forge test --mc ShadowbookTest
毎回新しいコピーで 9 回走らせ、9 回とも 27 passed; 1 failed だった。
失敗するのは fuzz テストだ。反例は回ごとに変わるが、いつも exact output の売り(args に true, false)、つまり編集した経路だけだ。そのうちの 1 回を示す。
[FAIL: assertion failed: 2462000000000000000000000000000000000000 > 2461999999999957401600000000000000000000; counterexample: calldata=0x… args=[2462, true, false, 144, 500]] testFuzz_roundingFavoursHook(uint96,bool,bool,uint16,uint16) (runs: 29, …)
Suite result: FAILED. 27 passed; 1 failed; 0 skipped; …
swap する人は token1 を 2,462 単位求め、払った token0 が最小単位 1 つ分少なかった。つまり、出る量 × 1e36 が入る量 × bid を上回った。
「丸めを確かめるテストがあるのでは?」
test_sellToken0_exactOut_roundsUpInput は通ったままだ。その量は割り切れるか、入る量が 0 より大きいままだからだ。
1 単位の丸めの誤りを見つけられるのは、いろいろな量で確かめる不等式だけだ。
git checkout -- src で戻すと、forge test は 49 件通る状態に戻る。
確認すること
- hook が指定側の delta として
+|amountSpecified|を返したあとのamountToSwapと、そのときプールの swap が何をするかを言える。 - 4 種類の swap それぞれで指定側の通貨を言え、Shadowbook の delta の両半分の符号を言える。
- Shadowbook が入る側を
takeせず claim を mint する理由と、出る側の出どころを説明できる。 - 自分のトレースで、
mint、出る側のsettle、Filled、ゼロのSwap、そのあとのルーターの支払いと受け取りを見つけた。 - 出る側を払わないと
ERC20TransferFailed、次にCurrencyNotSettledになること、符号を逆にするとルーターの検査で止まること、丸めを 1 つ逆にすると fuzz テストが失敗することを見た。
次のレッスン8 では、断る hook、その入力を動かす keeper、hook を正しいアドレスに置くことについて、このコースで見てきたことをまとめる。
最後は、本番前のチェックリストで締める。