Verified contractExactUNLICENSED
EkuboSwapHandler
Address0x2a9c887d5eaa5524877d88d886629dc96eceee66
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- Via IR
- yes
- License
- UNLICENSED
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,796,190
- Creation transaction
- 0x8d08f4582b…757a7aea31
contracts/router/modules/EkuboSwapHandler.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "../interfaces/ISwapHandler.sol";
import "../../shared/interfaces/IERC20.sol";
interface IWETH9 {
function deposit() external payable;
function withdraw(uint256) external;
}
/**
* @title EkuboSwapHandler — Ekubo_V3 (liquidityType 33)
*
* Ekubo keeps every pool inside one Core singleton. There is NO usable public
* router: `Router.sol` exists in Ekubo's repo but is not deployed on mainnet,
* and every live integrator (0x Settler, CoW, 1inch) locks Core directly from
* its own executor. So does this handler.
*
* The flow is the standard singleton lock/callback, but Ekubo is aggressively
* gas-golfed: two of its entrypoints have vanity names chosen so their selector
* is literally 0x00000000, and they take NO abi arguments — Core reads them
* straight out of calldata. Everything below is ported from Ekubo's own source
* (github.com/EkuboProtocol/evm-contracts).
*
* 1. call Core `lock()` (0xf83d08ba) with our payload appended RAW
* 2. Core calls back `locked_6416899205(uint256 id)` — selector 0x00000000 —
* with our payload at msg.data[36:]
* 3. inside, call Core `swap_6269342730()` — also selector 0x00000000 — with
* exactly 132 bytes: selector ++ token0 ++ token1 ++ config ++ params
* 4. settle: startPayments -> transfer -> completePayments for the input,
* then withdraw the output straight to `to`
*
* `params` is a PACKED bytes32 (Ekubo's SwapParameters), not four words:
* [255:160] sqrtRatioLimit (uint96 float)
* [159:32] amount (int128; > 0 = exact-in)
* [31] isToken1
* [30:0] skipAhead
*
* `path.data` carries the PoolKey remainder: abi.encode(token0, token1, config).
* The pool cannot be identified without it — `config` packs
* extension(20B)++fee(uint64)++typeConfig(4B) and is NOT derivable from the
* token pair.
*
* FORWARD-ONLY EXTENSIONS (Ve33). Some extensions refuse a direct Core.swap
* (beforeSwap reverts SwapMustHappenThroughForward) and require the swap to be
* forwarded to them via Core.forward(extension) so they can account their own
* fee. The locker detects that exact revert and re-issues the same payload
* through forward; deltas/settlement are identical afterwards. Robinhood:
* 27 of the 30 live Ekubo pools are Ve33 pools.
*
* NATIVE ETH. Ekubo denotes native ETH as address(0), and a THIRD of its
* mainnet pools are native-paired, so they are served rather than skipped. Our
* route steps are WETH-normalised, so this handler bridges the two:
* - paying native : unwrap WETH, then send ETH to Core — its `receive()`
* credits the locker's debt (no startPayments dance)
* - receiving native: `withdraw` with token address(0) sends real ETH, so we
* take it here, wrap it, and forward WETH to `to`
* The route never sees anything but WETH.
*
* Slippage: no per-hop bound is imposed here — the sqrtRatioLimit is set to the
* extreme of the swap direction, exactly the uni_v4 model. Safety is the
* whole-route minReturn enforced by NonLinearSwapModule. We do require a FULL
* fill (see executeSwap) so a liquidity shortfall reverts loudly instead of
* silently leaving unspent input dust in the handler.
*/
contract EkuboSwapHandler is ISwapHandler {
/// Ekubo Core singleton. Immutable — nothing can repoint execution.
address public immutable core;
/// Canonical WETH, for bridging native-ETH pools to our WETH-normalised steps.
address public immutable weth;
/// Core `lock()`. Payload is appended raw after these 4 bytes.
bytes4 private constant SEL_LOCK = 0xf83d08ba;
/// Both `locked_6416899205(uint256)` and `swap_6269342730()` — vanity names
/// picked so the selector is zero. Verified with `cast sig`.
bytes4 private constant SEL_ZERO = 0x00000000;
bytes4 private constant SEL_START_PAYMENTS = 0xf9b6a796;
bytes4 private constant SEL_COMPLETE_PAYMENTS = 0x12e103f1;
bytes4 private constant SEL_WITHDRAW = 0x3ccfd60b;
/// Core `forward(address to)`: hands the lock context to an extension for
/// the duration of the call; any calldata after the address is passed to
/// the forwardee raw (IFlashAccountant.forward).
bytes4 private constant SEL_FORWARD = 0x101e8952;
/// `SwapMustHappenThroughForward()` — raised by Ekubo's forward-only
/// extensions (Ve33 on Robinhood: ve(3,3) dynamic voter fees, Core fee 0)
/// from beforeSwap when a locker calls Core.swap directly. Those pools are
/// swapped by forwarding the (PoolKey, SwapParameters) payload to the
/// extension instead; it performs the Core swap as the temporary locker,
/// adds its fee to the returned deltas and saves the fee in Core against
/// our lock, so settlement below is unchanged.
bytes4 private constant ERR_SWAP_MUST_FORWARD = 0x0ad27a39;
/// Ekubo sqrt-ratio bounds in its uint96 FLOAT form (MIN/MAX_SQRT_RATIO_RAW
/// in src/types/sqrtRatio.sol). Selling token0 pushes price down (MIN);
/// selling token1 pushes it up (MAX).
uint96 private constant MIN_SQRT_RATIO = 4611797791050542631;
uint96 private constant MAX_SQRT_RATIO = 79227682466138141934206691491;
constructor(address _core, address _weth) {
require(_core != address(0), "Ekubo: core 0");
require(_weth != address(0), "Ekubo: weth 0");
core = _core;
weth = _weth;
}
/// Only Core (withdrawing native output) and WETH (on unwrap) ever send ETH
/// here. Anything else is a mistake, so reject it rather than silently
/// absorbing funds the next swap would sweep.
receive() external payable {
require(msg.sender == core || msg.sender == weth, "Ekubo: unexpected ETH");
}
function executeSwap(
PathDescription memory path,
uint256 amount,
address /* from */,
address to
) external override returns (uint256 amountOut) {
// amount == 0 -> use what the module just transferred in (the repo-wide
// pass-0 convention; also what makes fee-on-transfer intermediates work).
uint256 amountIn = amount == 0
? IERC20(path.srcToken).balanceOf(address(this))
: amount;
require(amountIn > 0 && amountIn <= uint256(uint128(type(int128).max)), "Ekubo: amountIn");
(address token0, address token1, bytes32 config) = abi.decode(
path.data,
(address, address, bytes32)
);
// Ekubo's address(0) is our WETH. Alias for direction detection only —
// the pool key itself keeps address(0).
address routeToken0 = token0 == address(0) ? weth : token0;
address routeToken1 = token1 == address(0) ? weth : token1;
// A WETH/native pool would alias both sides to WETH and make the
// direction undecidable. Ekubo has no such pool today; refuse rather
// than guess if one ever appears.
require(routeToken0 != routeToken1, "Ekubo: ambiguous pool");
bool isToken1;
if (path.srcToken == routeToken0) {
isToken1 = false;
} else if (path.srcToken == routeToken1) {
isToken1 = true;
} else {
revert("Ekubo: srcToken not in pool");
}
// Pack SwapParameters. amountIn < 2^127 (checked above) so bit 159 — the
// int128 sign bit — is clear, i.e. this is an exact-INPUT swap.
uint256 params = (uint256(isToken1 ? MAX_SQRT_RATIO : MIN_SQRT_RATIO) << 160) |
(amountIn << 32) |
(isToken1 ? (uint256(1) << 31) : 0);
// skipAhead (bits [30:0]) stays 0: no tick-bitmap skipping.
uint256 balBefore = IERC20(path.dstToken).balanceOf(to);
// Acquire the lock. Core appends nothing of its own — our payload comes
// back verbatim in the callback.
(bool ok, bytes memory ret) = core.call(
abi.encodePacked(
SEL_LOCK,
abi.encode(token0, token1, config, bytes32(params), isToken1, to, amountIn)
)
);
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 32), mload(ret))
}
}
// Sweep any native ETH left over once the lock closes. Observed on
// live BoostedFees-extension pools: Core returns a small amount to the
// locker beyond the settled deltas (~0.000577 ETH on a 0.1 WETH swap).
// Leaving it here would be a slow leak — the module passes amount=0 and
// handlers spend their own balance, so the next swap through this
// handler would silently pick it up and hand it to an unrelated user.
// Wrapping it to `to` keeps the value with the trade that produced it,
// and keeps this contract balance-free between calls.
uint256 residual = address(this).balance;
if (residual > 0) {
IWETH9(weth).deposit{value: residual}();
TransferHelper.safeTransfer(weth, to, residual);
}
// Measure what the recipient actually received rather than trusting the
// packed deltas (and their sign convention) a second time. Deliberately
// after the sweep: when dstToken IS WETH the swept amount is genuinely
// part of the output and must be counted.
amountOut = IERC20(path.dstToken).balanceOf(to) - balBefore;
require(amountOut > 0, "Ekubo: no output");
}
/**
* Core's lock callback. Selector is 0x00000000 by construction — solc
* derives it from this exact function name, same as Ekubo's own contracts.
*
* Only reachable from Core, and Core only ever calls back the address that
* called `lock()` — which is this contract, from executeSwap above.
*/
function locked_6416899205(uint256 /* id */) external {
require(msg.sender == core, "Ekubo: not core");
(
address token0,
address token1,
bytes32 config,
bytes32 params,
bool isToken1,
address to,
uint256 amountIn
) = abi.decode(msg.data[36:], (address, address, bytes32, bytes32, bool, address, uint256));
// swap_6269342730(): no abi args, Core reads 132 bytes of raw calldata.
// abi.encodeWithSelector gives exactly selector + 4 words.
(bool ok, bytes memory ret) = core.call(
abi.encodeWithSelector(SEL_ZERO, token0, token1, config, params)
);
if (!ok && ret.length == 4 && bytes4(ret) == ERR_SWAP_MUST_FORWARD) {
// Forward-only extension: same four words, delivered through the
// extension (first 20 bytes of the packed config word). The failed
// direct call changed nothing — beforeSwap reverted before Core
// touched any state — so the lock is intact.
address extension = address(bytes20(config));
(ok, ret) = core.call(
abi.encodePacked(
abi.encodeWithSelector(SEL_FORWARD, extension),
abi.encode(token0, token1, config, params)
)
);
}
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 32), mload(ret))
}
}
require(ret.length >= 32, "Ekubo: swap return");
// Returns balanceUpdate ++ stateAfter. balanceUpdate packs two int128
// deltas: delta0 in the high half, delta1 in the low half. POSITIVE =
// we owe Core; NEGATIVE = Core owes us.
bytes32 update;
assembly ("memory-safe") {
update := mload(add(ret, 32))
}
int128 delta0 = int128(uint128(uint256(update) >> 128));
int128 delta1 = int128(uint128(uint256(update)));
// Pool-space tokens: address(0) here means native ETH.
address tokenIn = isToken1 ? token1 : token0;
address tokenOut = isToken1 ? token0 : token1;
int128 deltaIn = isToken1 ? delta1 : delta0;
int128 deltaOut = isToken1 ? delta0 : delta1;
require(deltaIn > 0 && deltaOut < 0, "Ekubo: deltas");
uint256 owed = uint256(uint128(deltaIn));
uint128 received = uint128(-deltaOut);
// A short fill would leave unspent input sitting in the handler, which
// the next swap through this handler would sweep. Reject it instead.
require(owed == amountIn, "Ekubo: partial fill");
_pay(tokenIn, owed);
_collect(tokenOut, to, received);
// Raw-return the output amount; Core passes lock() returndata straight
// through to executeSwap (which cross-checks it against balances).
assembly ("memory-safe") {
mstore(0, received)
return(0, 32)
}
}
/// Settle the input side of the swap.
function _pay(address token, uint256 amount) private {
if (token == address(0)) {
// Native: the module handed us WETH, so unwrap and send real ETH.
// Core's receive() credits the locker's debt — no startPayments.
IWETH9(weth).withdraw(amount);
(bool sent, ) = core.call{value: amount}("");
require(sent, "Ekubo: native pay");
return;
}
// ERC20: startPayments(token) -> transfer -> completePayments(token).
// Both take the token list abi-encoded after the selector.
(bool ok, ) = core.call(abi.encodeWithSelector(SEL_START_PAYMENTS, token));
require(ok, "Ekubo: startPayments");
TransferHelper.safeTransfer(token, core, amount);
(ok, ) = core.call(abi.encodeWithSelector(SEL_COMPLETE_PAYMENTS, token));
require(ok, "Ekubo: completePayments");
}
/// Take the output side and deliver it to `to` as an ERC20.
/// withdraw() takes PACKED args, not abi-encoded:
/// selector ++ token(20) ++ recipient(20) ++ amount(16) = 60 bytes.
function _collect(address token, address to, uint128 amount) private {
// Native output arrives as real ETH, so take it here and wrap it —
// the route expects WETH.
address recipient = token == address(0) ? address(this) : to;
(bool ok, bytes memory ret) = core.call(
abi.encodePacked(SEL_WITHDRAW, token, recipient, amount)
);
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 32), mload(ret))
}
}
if (token == address(0)) {
IWETH9(weth).deposit{value: amount}();
TransferHelper.safeTransfer(weth, to, amount);
}
}
}
@uniswap/lib/contracts/libraries/TransferHelper.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
contracts/router/interfaces/ISwapHandler.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.20;
interface ISwapHandler {
struct PathDescription {
address srcToken;
address dstToken;
address pairAddr;
uint256 fee;
uint256 srcAmount;
uint256 dstMinAmount;
uint256 feeSrc;
uint256 feeDst;
uint256 liquidityType;
bytes data;
}
function executeSwap(
PathDescription memory path,
uint256 amount,
address from,
address to
) external returns (uint256 amountOut);
}contracts/shared/interfaces/IERC20.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}Compiler settingsShow
{
"viaIR": true,
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.