Verified contractPartialMIT
EkuboAdapter
Address0xe523406929f8e60d75448e55663145b370791f4e
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 1,000 runs
- EVM version
- osaka
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,290,357
- Creation transaction
- 0xacd58bd02f…4ef620d6f3
6 files
src/adapters/EkuboAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { IAdapter } from "src/interfaces/IAdapter.sol";
import { IEkuboCore } from "src/interfaces/venues/IEkuboCore.sol";
import { IEkuboV1Core } from "src/interfaces/venues/IEkuboV1Core.sol";
import { IWETH9 } from "src/interfaces/venues/IWETH9.sol";
import { SafeERC20Min } from "src/libraries/SafeERC20Min.sol";
/// @notice Ekubo adapter for `Router` ids 104 (`EKUBO_V3`, the v3 Core) and 105 (`EKUBO_V1`, the
/// v1 Core). Stateless: the `Router` transfers `amountIn` of `tokenIn` here, calls `swap`,
/// and the whole output, plus any input the pool did not take, is paid back to
/// `msg.sender` within the call.
///
/// Both Cores are flash-accounting singletons, held here as constants: `swap` opens a
/// `lock()` with the swap's inputs appended to its calldata, and the Core calls back
/// (`locked_6416899205` on v3, `locked` on v1) where the swap runs, the input is paid
/// and the output withdrawn. The callbacks, and v1's `payCallback`, accept only the Core
/// whose lock this adapter opened, and only while that lock is open.
///
/// The leg's `params` is the raw 256-bit PoolConfig word; the PoolKey is the two tokens
/// sorted, with the config. A config that names no pool for the pair reverts in Core.
/// `flags` bit 0 says the pool's WETH side is native ETH (`address(0)`, so always
/// `token0`): a WETH input is unwrapped and paid to Core by value (Core's `receive()`
/// credits the locker), and Core's `withdraw(address(0))` sends a native output from
/// Core itself, wrapped here before it is paid out.
///
/// Exact-in with the direction's extreme sqrt-ratio limit: no per-leg minimum, the
/// settler's floor on the route's end-to-end output is the guarantee. A shallow pool can
/// fill partially; the unfilled input goes back to `msg.sender`. Output is measured as a
/// balance difference, never from Core's deltas.
contract EkuboAdapter is IAdapter {
using SafeERC20Min for address;
/// @notice Ekubo v3 Core (id 104).
address public constant CORE_V3 = 0x00000000000014aA86C5d3c41765bb24e11bd701;
/// @notice Ekubo v1 Core (id 105), a different contract and ABI from the v3 Core.
address public constant CORE_V1 = 0xe0e0e08A6A4b9Dc7bD67BCB7aadE5cF48157d444;
uint8 internal constant EKUBO_V3 = 104;
uint8 internal constant EKUBO_V1 = 105;
/// @dev Ekubo's compact `uint96` sqrt-ratio bounds, identical in both Cores: a token0-in
/// swap (price decreasing) is bounded by MIN, a token1-in swap by MAX.
uint96 internal constant MIN_SQRT_RATIO = 4_611_797_791_050_542_631;
uint96 internal constant MAX_SQRT_RATIO = 79_227_682_466_138_141_934_206_691_491;
address public immutable WETH;
/// @dev Transient slot holding the Core of the `swap` in progress, 0 otherwise: set before
/// the Core's lock opens, cleared after the payouts. It gates the callbacks and `swap`
/// re-entry, and is the only non-WETH sender `receive` accepts ETH from.
bytes32 private constant _CORE_SLOT = keccak256("router-contracts.v1.EkuboAdapter.core");
error NotCore();
error BadProtocol();
error BadFlags();
error TokenMismatch();
error AmountTooLarge();
error NoOutput();
error Locked();
error PaymentFailed();
constructor(address weth) {
WETH = weth;
}
/// @dev ETH arrives only from unwrapping WETH or as the locked Core's native `withdraw`.
receive() external payable {
if (msg.sender != WETH && msg.sender != _lockedCore()) revert NotCore();
}
/// @inheritdoc IAdapter
function swap(
address,
uint8 protocolId,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 params,
uint8 flags
) external returns (uint256 amountOut) {
if (_lockedCore() != address(0)) revert Locked();
address core;
if (protocolId == EKUBO_V3) core = CORE_V3;
else if (protocolId == EKUBO_V1) core = CORE_V1;
else revert BadProtocol();
if (flags > 1) revert BadFlags();
if (tokenIn == tokenOut) revert TokenMismatch();
if (amountIn > uint128(type(int128).max)) revert AmountTooLarge();
// The pool's spelling of the two tokens: with the native flag, the WETH side is
// `address(0)`, and exactly one side must be WETH.
address poolIn = tokenIn;
address poolOut = tokenOut;
if (flags == 1) {
if (tokenIn == WETH) {
poolIn = address(0);
IWETH9(WETH).withdraw(amountIn);
} else if (tokenOut == WETH) {
poolOut = address(0);
} else {
revert TokenMismatch();
}
}
uint256 before = tokenOut.balanceOf(address(this));
_setLockedCore(core);
if (core == CORE_V3) _lockV3(poolIn, poolOut, amountIn, bytes32(params));
else _lockV1(poolIn, poolOut, amountIn, bytes32(params));
// A native output, or the native input the pool did not take, is wrapped back.
uint256 eth = address(this).balance;
if (eth != 0) IWETH9(WETH).deposit{ value: eth }();
amountOut = tokenOut.balanceOf(address(this)) - before;
if (amountOut == 0) revert NoOutput();
tokenOut.safeTransfer(msg.sender, amountOut);
uint256 unfilled = tokenIn.balanceOf(address(this));
if (unfilled != 0) tokenIn.safeTransfer(msg.sender, unfilled);
// Released only after the payouts, so a hooked token cannot re-enter `swap` mid-payout.
_setLockedCore(address(0));
}
// ── v3 Core (id 104) ────────────────────────────────────────────────────
/// @dev `lock()` with `token0 ‖ token1 ‖ config ‖ swapParams` appended; Core forwards them to
/// `locked_6416899205` after `selector ‖ id`, at offsets 36, 68, 100, 132.
/// `swapParams` = `sqrtRatioLimit << 160 | amount << 32 | isToken1 << 31` (exact-in,
/// no skip-ahead).
function _lockV3(address poolIn, address poolOut, uint256 amountIn, bytes32 config) private {
bool isToken1 = poolIn > poolOut;
(address token0, address token1) = isToken1 ? (poolOut, poolIn) : (poolIn, poolOut);
bytes32 swapParams = bytes32(
(uint256(isToken1 ? MAX_SQRT_RATIO : MIN_SQRT_RATIO) << 160) | (amountIn << 32)
| (isToken1 ? uint256(1 << 31) : 0)
);
_call(
CORE_V3,
abi.encodeWithSelector(IEkuboCore.lock.selector, token0, token1, config, swapParams)
);
}
/// @notice v3 Core lock callback (selector `0x00000000`): swap, pay the input, withdraw the
/// output. Only the v3 Core, only inside this adapter's own v3 lock.
function locked_6416899205(uint256) external {
_onlyLocking(CORE_V3);
address token0;
address token1;
bytes32 config;
bytes32 swapParams;
assembly ("memory-safe") {
token0 := calldataload(36)
token1 := calldataload(68)
config := calldataload(100)
swapParams := calldataload(132)
}
bool isToken1 = (uint256(swapParams) >> 31) & 1 == 1;
// `swap_6269342730` reads raw calldata: token0, token1, config, params as 32-byte words.
bytes memory ret = _call(
CORE_V3, abi.encodePacked(bytes4(0), abi.encode(token0, token1, config, swapParams))
);
uint256 update = abi.decode(ret, (uint256));
int128 delta0 = int128(int256(update >> 128));
int128 delta1 = int128(int256(update & type(uint128).max));
(int128 deltaIn, int128 deltaOut) = isToken1 ? (delta1, delta0) : (delta0, delta1);
if (deltaIn <= 0 || deltaOut >= 0) revert NoOutput();
(address tokenIn, address tokenOut) = isToken1 ? (token1, token0) : (token0, token1);
uint256 owed = uint128(deltaIn);
if (tokenIn == address(0)) {
_payNative(CORE_V3, owed);
} else {
// Core credits its balance difference between the two calls.
_call(CORE_V3, abi.encodeWithSelector(IEkuboCore.startPayments.selector, tokenIn));
tokenIn.safeTransfer(CORE_V3, owed);
_call(CORE_V3, abi.encodeWithSelector(IEkuboCore.completePayments.selector, tokenIn));
}
// Packed `token (20) ‖ recipient (20) ‖ amount (16)`.
_call(
CORE_V3,
abi.encodePacked(
IEkuboCore.withdraw.selector, tokenOut, address(this), uint128(-deltaOut)
)
);
}
// ── v1 Core (id 105) ────────────────────────────────────────────────────
/// @dev `lock()` with `token0 ‖ token1 ‖ config ‖ amount ‖ isToken1` appended; Core forwards
/// them to `locked` at offsets 36, 68, 100, 132, 164.
function _lockV1(address poolIn, address poolOut, uint256 amountIn, bytes32 config) private {
bool isToken1 = poolIn > poolOut;
(address token0, address token1) = isToken1 ? (poolOut, poolIn) : (poolIn, poolOut);
_call(
CORE_V1,
abi.encodeWithSelector(
IEkuboV1Core.lock.selector, token0, token1, config, amountIn, isToken1
)
);
}
/// @notice v1 Core lock callback (`0xb45a3c0e`): swap, pay the input, withdraw the output.
/// Only the v1 Core, only inside this adapter's own v1 lock.
function locked(uint256) external {
_onlyLocking(CORE_V1);
address token0;
address token1;
bytes32 config;
uint256 amount;
bool isToken1;
assembly ("memory-safe") {
token0 := calldataload(36)
token1 := calldataload(68)
config := calldataload(100)
amount := calldataload(132)
isToken1 := iszero(iszero(calldataload(164)))
}
(int128 delta0, int128 delta1) = IEkuboV1Core(CORE_V1)
.swap_611415377(
IEkuboV1Core.PoolKey(token0, token1, config),
int128(uint128(amount)),
isToken1,
isToken1 ? MAX_SQRT_RATIO : MIN_SQRT_RATIO,
0
);
(int128 deltaIn, int128 deltaOut) = isToken1 ? (delta1, delta0) : (delta0, delta1);
if (deltaIn <= 0 || deltaOut >= 0) revert NoOutput();
(address tokenIn, address tokenOut) = isToken1 ? (token1, token0) : (token0, token1);
uint256 owed = uint128(deltaIn);
if (tokenIn == address(0)) {
_payNative(CORE_V1, owed);
} else {
// `pay` credits Core's balance difference around `payCallback`; the owed amount
// rides after the token word and reaches the callback at offset 68.
_call(CORE_V1, abi.encodeWithSelector(IEkuboV1Core.pay.selector, tokenIn, owed));
}
IEkuboV1Core(CORE_V1).withdraw(tokenOut, address(this), uint128(-deltaOut));
}
/// @notice v1 Core payment callback (`0x599d0714`), entered during the `pay(token)` that
/// `locked` issues: transfers the owed amount (calldata offset 68) to Core. Only the
/// v1 Core, only inside this adapter's own v1 lock.
function payCallback(uint256, address token) external {
_onlyLocking(CORE_V1);
uint256 amount;
assembly ("memory-safe") {
amount := calldataload(68)
}
token.safeTransfer(CORE_V1, amount);
}
// ── shared ──────────────────────────────────────────────────────────────
function _onlyLocking(address core) private view {
if (msg.sender != core || _lockedCore() != core) revert NotCore();
}
/// @dev A native debt is paid by value to Core's `receive()`, which credits the locker.
function _payNative(address core, uint256 owed) private {
(bool ok,) = core.call{ value: owed }("");
if (!ok) revert PaymentFailed();
}
/// @dev Raw call to a Core; its revert data is bubbled verbatim.
function _call(address core, bytes memory data) private returns (bytes memory ret) {
bool ok;
(ok, ret) = core.call(data);
if (!ok) {
assembly ("memory-safe") {
revert(add(ret, 32), mload(ret))
}
}
}
function _lockedCore() private view returns (address core) {
bytes32 slot = _CORE_SLOT;
assembly ("memory-safe") {
core := tload(slot)
}
}
function _setLockedCore(address core) private {
bytes32 slot = _CORE_SLOT;
assembly ("memory-safe") {
tstore(slot, core)
}
}
}
src/interfaces/IAdapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice A non-core leg's executor (RFC "Router": adapter families and the pAMM adapter). The
/// `Router` reaches it by `call`, never `delegatecall`, at an address that is immutable
/// in the `Router`'s code.
///
/// Funding: the `Router` transfers `amountIn` of `tokenIn` to the adapter before the call.
/// The adapter pays the whole output to `msg.sender` within the call and holds nothing
/// after it. The `Router` measures its own `tokenOut` balance across the call and uses
/// that, not the return value.
interface IAdapter {
/// @param pool The pool or venue the leg carries (Curve, Fluid, pAMM ids), or
/// `address(0)` for ids whose adapter holds its own cores (Ekubo).
/// @param protocolId The leg's 8-bit id, so one adapter can serve several ids of one family.
/// @param params The leg's right-aligned params field: Ekubo's raw 256-bit pool config,
/// 0 for ids that carry none.
/// @param flags The leg's 8 flag bits; their meaning is per family (Curve: i 4 | j 4).
function swap(
address pool,
uint8 protocolId,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 params,
uint8 flags
) external returns (uint256 amountOut);
}
src/interfaces/venues/IEkuboCore.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Ekubo v3 Core (mainnet singleton `0x00000000000014aA86C5d3c41765bb24e11bd701`), the
/// surface `EkuboAdapter` uses for `Router` id 104.
///
/// Flash accounting: every swap runs inside `lock()`, which calls
/// `locked_6416899205(uint256 id)` (selector `0x00000000`) back on `msg.sender` with any
/// calldata that followed `lock()`'s selector appended after `id` (readable from offset 36
/// in the callback). Every debt must be zero when `lock()` returns.
///
/// Most entry points read raw calldata, not standard ABI:
/// - `swap_6269342730` (selector `0x00000000`): `token0 ‖ token1 ‖ config ‖ params`, each a
/// 32-byte word; returns one `PoolBalanceUpdate` word
/// `delta0 (int128) << 128 | delta1 (int128)`, pool perspective (positive = the locker
/// owes Core, negative = Core owes the locker).
/// - `SwapParameters`: `sqrtRatioLimit (uint96) << 160 | isExactOut << 159 |
/// amount (int128) << 32 | isToken1 << 31 | skipAhead (31 bits)`.
/// - `startPayments` / `completePayments`: token addresses as 32-byte words after the
/// selector; Core credits its `balanceOf` difference across the two calls, so a native
/// (`address(0)`) debt cannot be paid this way: it is paid by value to Core's
/// `receive()`, which credits the current locker.
/// - `withdraw`: packed `token (20) ‖ recipient (20) ‖ amount (16)` tuples. `token == 0`
/// is a value transfer from Core to the recipient.
///
/// Native ETH is `address(0)`, so in a PoolKey it is always `token0`.
interface IEkuboCore {
function lock() external;
function swap_6269342730() external payable;
function startPayments() external;
function completePayments() external;
function withdraw() external;
}
src/interfaces/venues/IEkuboV1Core.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Ekubo v1 Core (mainnet singleton `0xe0e0e08A6A4b9Dc7bD67BCB7aadE5cF48157d444`), the
/// surface `EkuboAdapter` uses for `Router` id 105. A different contract and ABI from the
/// v3 Core (`IEkuboCore`); the two share only `lock()`.
///
/// `lock()` calls `locked(uint256 id)` (`0xb45a3c0e`) back on `msg.sender`, appending any
/// calldata that followed `lock()`'s selector after `id` (offset 36). Every debt must be
/// zero when `lock()` returns.
///
/// `swap_611415377` (selector `0x00000000`) is standard ABI and returns the two
/// pool-perspective deltas (positive = the locker owes Core). A zero `sqrtRatioLimit`
/// reverts: v1 substitutes no default.
///
/// ERC20 debts are paid through `pay(token)`: Core reads its balance, calls
/// `payCallback(id, token)` (`0x599d0714`) back on the locker, and credits the difference,
/// so the transfer must happen inside the callback. Calldata after `pay`'s token word is
/// forwarded after the callback's two arguments (offset 68). `pay` refuses native ETH;
/// a native debt is paid by value to Core's `receive()`, which credits the current locker.
/// `withdraw(address(0), …)` sends ETH from Core.
interface IEkuboV1Core {
/// @notice `config` packs `extension (20) | fee (uint64) | tickSpacing (uint32)`.
struct PoolKey {
address token0;
address token1;
bytes32 config;
}
function lock() external;
function swap_611415377(
PoolKey calldata poolKey,
int128 amount,
bool isToken1,
uint96 sqrtRatioLimit,
uint256 skipAhead
) external payable returns (int128 delta0, int128 delta1);
function pay(address token) external returns (uint128 payment);
function withdraw(address token, address recipient, uint128 amount) external;
}
src/interfaces/venues/IWETH9.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Canonical WETH: wrap and unwrap, for V4 pools whose WETH side is native ETH.
interface IWETH9 {
function deposit() external payable;
function withdraw(uint256 amount) external;
}
src/libraries/SafeERC20Min.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @notice Minimal ERC20 surface for `SafeERC20Min`: empty returndata is success (USDT), a
/// returned word is the bool it claims.
interface IERC20Min {
function balanceOf(address) external view returns (uint256);
function transferFrom(address, address, uint256) external returns (bool);
function transfer(address, uint256) external returns (bool);
}
library SafeERC20Min {
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
_call(token, abi.encodeWithSelector(IERC20Min.transferFrom.selector, from, to, amount));
}
function safeTransfer(address token, address to, uint256 amount) internal {
_call(token, abi.encodeWithSelector(IERC20Min.transfer.selector, to, amount));
}
function balanceOf(address token, address who) internal view returns (uint256) {
return IERC20Min(token).balanceOf(who);
}
function _call(address token, bytes memory data) private {
(bool ok, bytes memory ret) = token.call(data);
require(ok && (ret.length == 0 || abi.decode(ret, (bool))), "erc20 call failed");
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 1000,
"enabled": true
},
"evmVersion": "osaka",
"remappings": [
"forge-std/=lib/forge-std/src/",
"priority-update-registry/=vendor/priority-update-registry/src/",
"solady/=lib/priority-update-registry/lib/solady/src/",
"@openzeppelin/=lib/priority-update-registry/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/priority-update-registry/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/priority-update-registry/lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.