Skip to content
Verified contractExactUNLICENSED

AngstromSwapHandler

Address0xb5083810929ef70bc4ec24cb7ff33adf72ac397d
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
26,155,006
Creation transaction
0xf8f466cfd8…9bab8aff29

contracts/router/modules/AngstromSwapHandler.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";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

/// @notice Uniswap v4 PoolManager surface (v4-core src/interfaces/IPoolManager.sol,
///         src/types/PoolKey.sol). Ethereum PoolManager 0x000000000004444c5dc75cB358380D2e3dE08A90.
interface IAngstromPoolManager {
    /// @dev Currency and IHooks are address types in v4-core.
    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    struct SwapParams {
        bool zeroForOne;
        /// @dev exact input = amountSpecified < 0.
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
    }

    /// @dev Calls IUnlockCallback(msg.sender).unlockCallback(data), then reverts
    ///      CurrencyNotSettled() if a currency delta is not zero.
    function unlock(bytes calldata data) external returns (bytes memory result);

    /// @return swapDelta The BalanceDelta of the caller: amount0 in the upper 128 bits,
    ///         amount1 in the lower 128 bits. Negative = the caller owes the PoolManager,
    ///         positive = the PoolManager owes the caller.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (int256 swapDelta);

    /// @dev Records the PoolManager balance of `currency` as the reserve for the next settle().
    function sync(address currency) external;

    /// @dev Credits msg.sender with (balance - synced reserve).
    function settle() external payable returns (uint256 paid);

    /// @dev Debits msg.sender with `amount` and transfers it to `to`.
    function take(address currency, address to, uint256 amount) external;

    function extsload(bytes32 slot) external view returns (bytes32 value);
}

/// @notice v4-core src/interfaces/callback/IUnlockCallback.sol
interface IAngstromUnlockCallback {
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

/// @notice The read surface of the Angstrom hook that this handler uses.
interface IAngstromHookLock {
    /// @dev Angstrom exposes extsload(uint256) (selector 0x7cf98081), not the v4 extsload(bytes32).
    ///      Slot 3, low 64 bits = _lastBlockUpdated (TopLevelAuth.sol).
    function extsload(uint256 slot) external view returns (uint256 value);
}

/**
 * @title AngstromSwapHandler (router, liquidityType 40, pool_type "uni_v4_angstrom")
 * @notice Router-side handler for the Uniswap v4 pools of the Angstrom hook (Sorella Labs).
 *         Ethereum hook 0x0000000aa232009084Bd71A5797d089AA4Edfad4.
 *
 * The hook lets a swap through only in a block that it saw "unlocked": a node bundle ran
 * in the block, or a node signed an empty-block attestation for the block. An attestation
 * is the hookData node (20 bytes) ++ EIP-712 signature (65 bytes) over
 * AttestAngstromBlockEmpty(uint64 block_number). It is valid in exactly one block.
 *
 * Path layout (the backend encodes it):
 *   path.pairAddr = the v4 PoolManager (immutable poolManager)
 *   path.fee      = 0x800000 (the dynamic-fee flag of every Angstrom pool key)
 *   path.data     = abi.encode(int24 tickSpacing, address hooks, bytes window)
 *   window        = k entries of 93 bytes, 0 <= k <= 11: uint64 block number (big endian)
 *                   ++ node (20) ++ signature (65). The backend sends the entries of the
 *                   blocks [head, head + 10].
 * PoolKey = {min(src, dst), max(src, dst), 0x800000, tickSpacing, hooks}; hooks must be
 * the immutable angstrom.
 *
 * Every window entry is a bearer credential: the signature binds only the block number,
 * not the caller, the pool or the swap. Anyone who reads the calldata can redeem an unused
 * entry in its block through the public hook function unlockWithEmptyAttestation, which
 * unlocks the hook for that block (a node bundle in that block then reverts
 * OnlyOncePerBlock). The handler therefore refuses a window of more than 11 entries.
 *
 * Execution:
 *   pick the first window entry whose block number equals block.number and pass its node ++
 *   signature as hookData. With no such entry, read the hook lock word (extsload(3)): when
 *   its low 64 bits equal block.number, a bundle or another taker already unlocked the
 *   hook in this block and the swap continues with empty hookData. Else revert
 *   AngstromAttestationMissing(block.number): the step fails closed before any transfer.
 *   PoolManager.unlock(data) -> unlockCallback(data) (msg.sender must be the immutable
 *   poolManager) -> PoolManager.swap(key, {zeroForOne, -amountIn, 4x price band},
 *   hookData) -> sync(src), TransferHelper.safeTransfer of amountIn to the PoolManager,
 *   settle() -> take(dst, to, amountOut).
 * The handler pays with TransferHelper.safeTransfer, so a token without a bool return
 * value (USDT) works. It gives no approvals. The output goes directly to `to`; the return
 * value is the balance increase of `to`. The per-hop min-out is 0: the module checks the
 * total. Exact input only: a partial fill (the price band stops the swap) reverts, so no
 * input stays in the handler. A native-currency pool (address 0) reverts.
 *
 * No storage lock: the v4 PoolManager calls unlockCallback only on the contract that called
 * unlock, and only during that unlock, and a nested unlock reverts AlreadyUnlocked. The
 * poolManager is immutable and path.pairAddr must equal it, so msg.sender == poolManager
 * is enough (the v4-periphery SafeCallback rule). A swap writes no handler storage, so the
 * gas-capped primary of wrapper 98 pays no SSTORE whose refund comes only at the end of
 * the transaction.
 */
contract AngstromSwapHandler is ISwapHandler, IAngstromUnlockCallback, Ownable {
    /// @notice No window entry for this block, and the hook is locked in this block.
    error AngstromAttestationMissing(uint64 blockNumber);

    /// @dev The fee of every Angstrom pool key: LPFeeLibrary.DYNAMIC_FEE_FLAG.
    uint24 internal constant DYNAMIC_FEE_FLAG = 0x800000;
    /// @dev One window entry: uint64 block number (8, big endian) ++ node (20) ++ signature (65).
    uint256 internal constant ENTRY_LEN = 93;
    /// @dev node (20) ++ signature (65): the hookData of an attestation.
    uint256 internal constant ATTESTATION_LEN = 85;
    /// @dev The longest window: the blocks [head, head + 10]. Each entry is a bearer credential,
    ///      so a longer window only exposes more attestations.
    uint256 internal constant MAX_WINDOW_ENTRIES = 11;
    /// @dev Angstrom TopLevelAuth storage slot of `uint64 _lastBlockUpdated` (low 64 bits).
    uint256 internal constant HOOK_LOCK_SLOT = 3;
    /// @dev PoolManager._pools mapping slot (v4-periphery StateLibrary.POOLS_SLOT).
    bytes32 internal constant POOLS_SLOT = bytes32(uint256(6));
    // TickMath bounds of Uniswap v4: MIN_SQRT_PRICE + 1 and MAX_SQRT_PRICE - 1.
    uint160 internal constant MIN_SQRT_PRICE_PLUS_1 = 4295128740;
    uint160 internal constant MAX_SQRT_PRICE_MINUS_1 = 1461446703485210103287273052203988822378723970341;

    address public immutable poolManager;
    address public immutable angstrom;

    constructor(address poolManager_, address angstrom_) Ownable(msg.sender) {
        require(poolManager_ != address(0) && angstrom_ != address(0), "angstrom: zero address");
        poolManager = poolManager_;
        angstrom = angstrom_;
    }

    function executeSwap(
        PathDescription memory path,
        uint256 amount,
        address, /* from */
        address to
    ) external override returns (uint256 amountOut) {
        require(path.pairAddr == poolManager, "angstrom: pool manager");
        require(path.fee == DYNAMIC_FEE_FLAG, "angstrom: fee");
        require(path.srcToken != address(0) && path.dstToken != address(0), "angstrom: native currency");
        require(path.srcToken != path.dstToken, "angstrom: same token");

        // amount == 0 resolves to our own balance: exactly what the module transferred in.
        uint256 amountIn = amount == 0 ? IERC20(path.srcToken).balanceOf(address(this)) : amount;
        require(amountIn > 0, "angstrom: zero input");
        // The PoolManager accounts deltas as int128.
        require(amountIn <= uint256(uint128(type(int128).max)), "angstrom: input too large");

        (int24 tickSpacing, address hooks, bytes memory window) = abi.decode(path.data, (int24, address, bytes));
        require(hooks == angstrom, "angstrom: hooks");
        require(window.length % ENTRY_LEN == 0, "angstrom: window layout");
        require(window.length <= MAX_WINDOW_ENTRIES * ENTRY_LEN, "angstrom: window too long");

        bytes memory hookData = _select(window, uint64(block.number));
        if (hookData.length == 0) {
            // No entry for this block: continue only when a node bundle or another taker
            // already unlocked the hook in this block. Else fail closed.
            uint64 lastBlockUpdated = uint64(IAngstromHookLock(angstrom).extsload(HOOK_LOCK_SLOT));
            if (lastBlockUpdated != uint64(block.number)) revert AngstromAttestationMissing(uint64(block.number));
        }

        bool zeroForOne = path.srcToken < path.dstToken;
        IAngstromPoolManager.PoolKey memory key = IAngstromPoolManager.PoolKey({
            currency0: zeroForOne ? path.srcToken : path.dstToken,
            currency1: zeroForOne ? path.dstToken : path.srcToken,
            fee: DYNAMIC_FEE_FLAG,
            tickSpacing: tickSpacing,
            hooks: hooks
        });

        uint256 before = IERC20(path.dstToken).balanceOf(to);
        IAngstromPoolManager(poolManager).unlock(abi.encode(key, zeroForOne, amountIn, to, hookData));

        amountOut = IERC20(path.dstToken).balanceOf(to) - before;
        require(amountOut > 0, "angstrom: zero output");
    }

    /// @notice PoolManager unlock callback. Only the PoolManager may call it. The PoolManager calls it
    ///         only during an unlock that this handler started in executeSwap, with the data that
    ///         executeSwap encoded.
    /// @return abi.encode(uint256 amountOut) where amountOut is the amount taken to `to`.
    function unlockCallback(bytes calldata data) external override returns (bytes memory) {
        address pm = poolManager;
        require(msg.sender == pm, "angstrom: not pool manager");
        (
            IAngstromPoolManager.PoolKey memory key,
            bool zeroForOne,
            uint256 amountIn,
            address to,
            bytes memory hookData
        ) = abi.decode(data, (IAngstromPoolManager.PoolKey, bool, uint256, address, bytes));

        int256 delta = IAngstromPoolManager(pm).swap(
            key,
            IAngstromPoolManager.SwapParams({
                zeroForOne: zeroForOne,
                amountSpecified: -int256(amountIn), // exact input
                sqrtPriceLimitX96: _priceLimit(pm, key, zeroForOne)
            }),
            hookData
        );

        int128 amount0 = int128(delta >> 128);
        int128 amount1 = int128(delta);
        (int128 inDelta, int128 outDelta) = zeroForOne ? (amount0, amount1) : (amount1, amount0);
        // Exact input: the input side is owed to the PoolManager, the output side is owed to us.
        require(inDelta < 0 && outDelta > 0, "angstrom: unexpected delta");
        require(uint256(uint128(-inDelta)) == amountIn, "angstrom: partial fill");
        uint256 amountOut = uint256(uint128(outDelta));

        (address srcToken, address dstToken) = zeroForOne ? (key.currency0, key.currency1) : (key.currency1, key.currency0);
        IAngstromPoolManager(pm).sync(srcToken);
        // TransferHelper accepts a token that returns no data (USDT); a plain
        // require(transfer(...)) reverts on it.
        TransferHelper.safeTransfer(srcToken, pm, amountIn);
        IAngstromPoolManager(pm).settle();
        IAngstromPoolManager(pm).take(dstToken, to, amountOut);
        return abi.encode(amountOut);
    }

    /// @dev The first window entry whose block number equals bn, as node ++ signature
    ///      (85 bytes); empty when no entry matches. The caller checks window.length % 93 == 0.
    function _select(bytes memory window, uint64 bn) internal pure returns (bytes memory hookData) {
        uint256 n = window.length / ENTRY_LEN;
        for (uint256 i; i < n; ++i) {
            uint256 entry; // memory address of entry i
            uint64 entryBlock;
            assembly ("memory-safe") {
                entry := add(add(window, 32), mul(i, ENTRY_LEN))
                entryBlock := shr(192, mload(entry))
            }
            if (entryBlock == bn) {
                hookData = new bytes(ATTESTATION_LEN); // 96 bytes of data space
                assembly ("memory-safe") {
                    let dst := add(hookData, 32)
                    // entry bytes [8, 72) -> hookData [0, 64)
                    mstore(dst, mload(add(entry, 8)))
                    mstore(add(dst, 32), mload(add(entry, 40)))
                    // entry bytes [72, 93) -> hookData [64, 85): the low 21 bytes of the
                    // word that ends at the entry end, moved up; the 11 padding bytes are zero.
                    mstore(add(dst, 64), shl(88, mload(add(entry, 61))))
                }
                return hookData;
            }
        }
    }

    /// @dev 4x price band around the current price (AkkaV4Router._getSqrtPriceLimit).
    function _priceLimit(address pm, IAngstromPoolManager.PoolKey memory key, bool zeroForOne)
        internal
        view
        returns (uint160)
    {
        bytes32 poolId = keccak256(abi.encode(key));
        uint160 current = uint160(uint256(IAngstromPoolManager(pm).extsload(keccak256(abi.encode(poolId, POOLS_SLOT)))));
        if (current == 0) return zeroForOne ? MIN_SQRT_PRICE_PLUS_1 : MAX_SQRT_PRICE_MINUS_1;
        if (zeroForOne) {
            uint256 lowered = uint256(current) / 2;
            return lowered <= MIN_SQRT_PRICE_PLUS_1 ? MIN_SQRT_PRICE_PLUS_1 : uint160(lowered);
        }
        uint256 raised = uint256(current) * 2;
        return raised >= MAX_SQRT_PRICE_MINUS_1 ? MAX_SQRT_PRICE_MINUS_1 : uint160(raised);
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@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.