Skip to content
Verified contractExactMIT

IntentSettlement

Address0xf59ba65b7664dd2f3404e16b06f2edc21a96acf4
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,870,899
Creation transaction
0x92dd7da792…05bcf7ab61

contracts/IntentSettlement.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

/// @notice Atomic exact-input intent settlement for allow-listed Polygon pools.
/// @dev Compile with evmVersion=cancun. Transient storage (EIP-1153) protects
///      reentrancy and authenticates V3/Algebra callbacks without persistent SSTOREs.
contract IntentSettlement {
    error AlreadyFilled();
    error BadRoute();
    error BadSignature();
    error CallbackUnauthorized();
    error DeadlineExpired();
    error InsufficientOutput();
    error NotAllowed();
    error Reentrancy();
    error TokenTransferFailed();
    error ZeroAddress();

    event IntentSettled(
        bytes32 indexed orderId,
        address indexed user,
        address sellToken,
        address buyToken,
        uint256 sellAmount,
        uint256 buyAmount,
        uint256 userAmount,
        uint256 surplus,
        address solver
    );
    event SolverSet(address indexed solver, bool allowed);
    event TargetSet(address indexed target, bool allowed);
    event OwnerSet(address indexed owner);
    event SurplusRecipientSet(address indexed recipient);

    uint8 private constant V2 = 0;
    uint8 private constant V3 = 1;
    uint8 private constant ALGEBRA = 2;
    uint8 private constant BALANCER_WEIGHTED = 3;
    uint8 private constant GIVEN_IN = 0;
    uint256 private constant PPM = 1_000_000;
    uint160 private constant MIN_SQRT_RATIO_PLUS_ONE = 4_295_128_740;
    uint160 private constant MAX_SQRT_RATIO_MINUS_ONE =
        1_461_446_703_485_210_103_287_273_052_203_988_822_378_723_970_341;
    bytes4 private constant EIP1271_MAGIC_VALUE = 0x1626ba7e;
    uint256 private constant SECP256K1N_HALF =
        0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0;

    uint256 private constant T_LOCK_SLOT = uint256(keccak256("intent.solver.transient.lock"));
    uint256 private constant T_CALLBACK_POOL_SLOT =
        uint256(keccak256("intent.solver.transient.callback.pool"));
    uint256 private constant T_CALLBACK_TOKEN_SLOT =
        uint256(keccak256("intent.solver.transient.callback.token"));
    uint256 private constant T_CALLBACK_AMOUNT_SLOT =
        uint256(keccak256("intent.solver.transient.callback.amount"));

    bytes32 public constant INTENT_TYPEHASH = keccak256(
        "Intent(bytes32 orderId,address user,address sellToken,address buyToken,uint256 sellAmount,uint256 minBuyAmount,uint48 validTo)"
    );
    bytes32 private constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
    bytes32 private constant NAME_HASH = keccak256("Polygon Intent Settlement");
    bytes32 private constant VERSION_HASH = keccak256("1");

    struct Intent {
        bytes32 orderId;
        address user;
        address sellToken;
        address buyToken;
        uint256 sellAmount;
        uint256 minBuyAmount;
        uint48 validTo;
        bytes signature;
    }

    struct Step {
        uint8 kind;
        address pool;
        address tokenIn;
        address tokenOut;
        uint256 minAmountOut;
        bytes auxData;
    }

    struct Route {
        uint256 amountIn;
        Step[] steps;
    }

    address public owner;
    address public surplusRecipient;
    mapping(address => bool) public solver;
    mapping(address => bool) public allowedTarget;
    mapping(bytes32 => bool) private _filled;

    constructor(address initialOwner, address initialSolver, address initialSurplusRecipient) {
        if (initialOwner == address(0) || initialSolver == address(0) || initialSurplusRecipient == address(0)) {
            revert ZeroAddress();
        }
        owner = initialOwner;
        solver[initialSolver] = true;
        surplusRecipient = initialSurplusRecipient;
        emit OwnerSet(initialOwner);
        emit SolverSet(initialSolver, true);
        emit SurplusRecipientSet(initialSurplusRecipient);
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotAllowed();
        _;
    }

    function setOwner(address next) external onlyOwner {
        if (next == address(0)) revert ZeroAddress();
        owner = next;
        emit OwnerSet(next);
    }

    function setSolver(address account, bool allowed) external onlyOwner {
        solver[account] = allowed;
        emit SolverSet(account, allowed);
    }

    function setTarget(address target, bool allowed) external onlyOwner {
        allowedTarget[target] = allowed;
        emit TargetSet(target, allowed);
    }

    function setSurplusRecipient(address recipient) external onlyOwner {
        if (recipient == address(0)) revert ZeroAddress();
        surplusRecipient = recipient;
        emit SurplusRecipientSet(recipient);
    }

    function isFilled(bytes32 orderId) external view returns (bool) {
        return _filled[orderId];
    }

    function domainSeparator() public view returns (bytes32) {
        return keccak256(
            abi.encode(DOMAIN_TYPEHASH, NAME_HASH, VERSION_HASH, block.chainid, address(this))
        );
    }

    function settle(
        Intent calldata intent,
        Route[] calldata routes,
        uint256 minSolverSurplus,
        address requestedRecipient
    ) external returns (uint256 surplus) {
        if (!solver[msg.sender] || requestedRecipient != surplusRecipient) revert NotAllowed();
        _enter();
        if (block.timestamp > intent.validTo) revert DeadlineExpired();
        if (_filled[intent.orderId]) revert AlreadyFilled();
        if (
            intent.user == address(0) || intent.sellToken == intent.buyToken ||
            intent.sellAmount == 0 || intent.minBuyAmount == 0
        ) revert BadRoute();
        _verify(intent);
        _filled[intent.orderId] = true;

        uint256 sellBefore = _balanceOf(intent.sellToken, address(this));
        uint256 buyBefore = _balanceOf(intent.buyToken, address(this));
        _safeTransferFrom(intent.sellToken, intent.user, address(this), intent.sellAmount);
        if (_balanceOf(intent.sellToken, address(this)) - sellBefore != intent.sellAmount) {
            revert TokenTransferFailed();
        }

        uint256 routed;
        uint256 routeCount = routes.length;
        for (uint256 i; i < routeCount;) {
            Route calldata route = routes[i];
            if (route.amountIn == 0 || route.steps.length == 0) revert BadRoute();
            routed += route.amountIn;
            uint256 amount = route.amountIn;
            address currentToken = intent.sellToken;
            uint256 stepCount = route.steps.length;
            for (uint256 j; j < stepCount;) {
                Step calldata step = route.steps[j];
                if (
                    !allowedTarget[step.pool] || step.tokenIn != currentToken ||
                    step.tokenIn == step.tokenOut || step.minAmountOut == 0
                ) revert BadRoute();
                amount = _execute(step, amount);
                currentToken = step.tokenOut;
                unchecked { ++j; }
            }
            if (currentToken != intent.buyToken) revert BadRoute();
            unchecked { ++i; }
        }
        if (routed != intent.sellAmount) revert BadRoute();

        uint256 bought = _balanceOf(intent.buyToken, address(this)) - buyBefore;
        if (bought < intent.minBuyAmount) revert InsufficientOutput();
        surplus = bought - intent.minBuyAmount;
        if (surplus < minSolverSurplus) revert InsufficientOutput();
        _safeTransfer(intent.buyToken, intent.user, intent.minBuyAmount);
        if (surplus != 0) _safeTransfer(intent.buyToken, requestedRecipient, surplus);

        _emitIntentSettled(intent, bought, surplus);
        _exit();
    }

    function _emitIntentSettled(
        Intent calldata intent,
        uint256 bought,
        uint256 surplus
    ) private {
        emit IntentSettled(
            intent.orderId,
            intent.user,
            intent.sellToken,
            intent.buyToken,
            intent.sellAmount,
            bought,
            intent.minBuyAmount,
            surplus,
            msg.sender
        );
    }

    function _execute(Step calldata step, uint256 amountIn) private returns (uint256 amountOut) {
        if (step.kind == V2) return _swapV2(step, amountIn);
        if (step.kind == V3) return _swapV3(step, amountIn, false);
        if (step.kind == ALGEBRA) return _swapV3(step, amountIn, true);
        if (step.kind == BALANCER_WEIGHTED) return _swapBalancer(step, amountIn);
        revert BadRoute();
    }

    function _swapV2(Step calldata step, uint256 amountIn) private returns (uint256 amountOut) {
        address token0 = IV2Pair(step.pool).token0();
        address token1 = IV2Pair(step.pool).token1();
        if (
            !((step.tokenIn == token0 && step.tokenOut == token1) ||
              (step.tokenIn == token1 && step.tokenOut == token0))
        ) revert BadRoute();
        bool zeroForOne = step.tokenIn == token0;
        (uint112 reserve0, uint112 reserve1,) = IV2Pair(step.pool).getReserves();
        (uint256 reserveIn, uint256 reserveOut) = zeroForOne
            ? (uint256(reserve0), uint256(reserve1))
            : (uint256(reserve1), uint256(reserve0));
        uint256 feePpm = abi.decode(step.auxData, (uint256));
        if (feePpm >= PPM) revert BadRoute();
        uint256 amountWithFee = amountIn * (PPM - feePpm);
        amountOut = amountWithFee * reserveOut / (reserveIn * PPM + amountWithFee);
        if (amountOut < step.minAmountOut) revert InsufficientOutput();
        _safeTransfer(step.tokenIn, step.pool, amountIn);
        if (zeroForOne) {
            IV2Pair(step.pool).swap(0, amountOut, address(this), "");
        } else {
            IV2Pair(step.pool).swap(amountOut, 0, address(this), "");
        }
    }

    function _swapV3(
        Step calldata step,
        uint256 amountIn,
        bool algebra
    ) private returns (uint256 amountOut) {
        address token0 = IV3Pool(step.pool).token0();
        address token1 = IV3Pool(step.pool).token1();
        if (
            !((step.tokenIn == token0 && step.tokenOut == token1) ||
              (step.tokenIn == token1 && step.tokenOut == token0))
        ) revert BadRoute();
        bool zeroForOne = step.tokenIn == token0;
        uint160 limit = abi.decode(step.auxData, (uint160));
        if (limit == 0) {
            limit = zeroForOne ? MIN_SQRT_RATIO_PLUS_ONE : MAX_SQRT_RATIO_MINUS_ONE;
        }
        uint256 beforeOut = _balanceOf(step.tokenOut, address(this));
        _setCallback(step.pool, step.tokenIn, amountIn);
        if (algebra) {
            IAlgebraPool(step.pool).swap(address(this), zeroForOne, int256(amountIn), limit, "");
        } else {
            IV3Pool(step.pool).swap(address(this), zeroForOne, int256(amountIn), limit, "");
        }
        _setCallback(address(0), address(0), 0);
        amountOut = _balanceOf(step.tokenOut, address(this)) - beforeOut;
        if (amountOut < step.minAmountOut) revert InsufficientOutput();
    }

    function _swapBalancer(Step calldata step, uint256 amountIn) private returns (uint256 amountOut) {
        bytes32 poolId = abi.decode(step.auxData, (bytes32));
        _forceApprove(step.tokenIn, step.pool, amountIn);
        IBalancerVault.SingleSwap memory single = IBalancerVault.SingleSwap({
            poolId: poolId,
            kind: GIVEN_IN,
            assetIn: step.tokenIn,
            assetOut: step.tokenOut,
            amount: amountIn,
            userData: ""
        });
        IBalancerVault.FundManagement memory funds = IBalancerVault.FundManagement({
            sender: address(this),
            fromInternalBalance: false,
            recipient: payable(address(this)),
            toInternalBalance: false
        });
        amountOut = IBalancerVault(step.pool).swap(
            single, funds, step.minAmountOut, block.timestamp
        );
        if (amountOut < step.minAmountOut) revert InsufficientOutput();
        _forceApprove(step.tokenIn, step.pool, 0);
    }

    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata
    ) external {
        _payCallback(amount0Delta, amount1Delta);
    }

    function algebraSwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata
    ) external {
        _payCallback(amount0Delta, amount1Delta);
    }

    function _payCallback(int256 amount0Delta, int256 amount1Delta) private {
        address expected;
        address expectedToken;
        uint256 remaining;
        uint256 poolSlot = T_CALLBACK_POOL_SLOT;
        uint256 tokenSlot = T_CALLBACK_TOKEN_SLOT;
        uint256 amountSlot = T_CALLBACK_AMOUNT_SLOT;
        assembly ("memory-safe") {
            expected := tload(poolSlot)
            expectedToken := tload(tokenSlot)
            remaining := tload(amountSlot)
        }
        if (msg.sender != expected || expected == address(0)) revert CallbackUnauthorized();
        address owedToken;
        uint256 owed;
        if (amount0Delta > 0) {
            owedToken = IV3Pool(msg.sender).token0();
            owed = uint256(amount0Delta);
        } else if (amount1Delta > 0) {
            owedToken = IV3Pool(msg.sender).token1();
            owed = uint256(amount1Delta);
        } else {
            revert BadRoute();
        }
        if (owedToken != expectedToken || owed > remaining) revert CallbackUnauthorized();
        assembly ("memory-safe") { tstore(amountSlot, 0) }
        _safeTransfer(owedToken, msg.sender, owed);
    }

    function _verify(Intent calldata intent) private view {
        bytes32 structHash = keccak256(
            abi.encode(
                INTENT_TYPEHASH,
                intent.orderId,
                intent.user,
                intent.sellToken,
                intent.buyToken,
                intent.sellAmount,
                intent.minBuyAmount,
                intent.validTo
            )
        );
        bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
        if (intent.user.code.length != 0) {
            (bool ok, bytes memory result) = intent.user.staticcall(
                abi.encodeWithSelector(IERC1271.isValidSignature.selector, digest, intent.signature)
            );
            if (!ok || result.length < 32 || abi.decode(result, (bytes4)) != EIP1271_MAGIC_VALUE) {
                revert BadSignature();
            }
            return;
        }
        if (_recover(digest, intent.signature) != intent.user) revert BadSignature();
    }

    function _recover(bytes32 digest, bytes calldata signature) private pure returns (address recovered) {
        bytes32 r;
        bytes32 s;
        uint8 v;
        if (signature.length == 65) {
            assembly ("memory-safe") {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 32))
                v := byte(0, calldataload(add(signature.offset, 64)))
            }
        } else if (signature.length == 64) {
            bytes32 vs;
            assembly ("memory-safe") {
                r := calldataload(signature.offset)
                vs := calldataload(add(signature.offset, 32))
            }
            s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            v = uint8((uint256(vs) >> 255) + 27);
        } else {
            return address(0);
        }
        if (uint256(s) > SECP256K1N_HALF || (v != 27 && v != 28)) return address(0);
        recovered = ecrecover(digest, v, r, s);
    }

    function _enter() private {
        uint256 slot = T_LOCK_SLOT;
        uint256 locked;
        assembly ("memory-safe") { locked := tload(slot) }
        if (locked != 0) revert Reentrancy();
        assembly ("memory-safe") {
            tstore(slot, 1)
        }
    }

    function _exit() private {
        uint256 slot = T_LOCK_SLOT;
        assembly ("memory-safe") { tstore(slot, 0) }
    }

    function _setCallback(address pool, address token, uint256 amount) private {
        uint256 poolSlot = T_CALLBACK_POOL_SLOT;
        uint256 tokenSlot = T_CALLBACK_TOKEN_SLOT;
        uint256 amountSlot = T_CALLBACK_AMOUNT_SLOT;
        assembly ("memory-safe") {
            tstore(poolSlot, pool)
            tstore(tokenSlot, token)
            tstore(amountSlot, amount)
        }
    }

    function _balanceOf(address token, address account) private view returns (uint256 value) {
        (bool ok, bytes memory result) = token.staticcall(
            abi.encodeWithSelector(IERC20.balanceOf.selector, account)
        );
        if (!ok || result.length < 32) revert TokenTransferFailed();
        value = abi.decode(result, (uint256));
    }

    function _safeTransfer(address token, address to, uint256 amount) private {
        _callOptionalReturn(token, abi.encodeWithSelector(IERC20.transfer.selector, to, amount));
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) private {
        _callOptionalReturn(
            token, abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)
        );
    }

    function _forceApprove(address token, address spender, uint256 amount) private {
        (bool ok, bytes memory result) = token.call(
            abi.encodeWithSelector(IERC20.approve.selector, spender, amount)
        );
        if (ok && (result.length == 0 || abi.decode(result, (bool)))) return;
        _callOptionalReturn(token, abi.encodeWithSelector(IERC20.approve.selector, spender, 0));
        _callOptionalReturn(token, abi.encodeWithSelector(IERC20.approve.selector, spender, amount));
    }

    function _callOptionalReturn(address token, bytes memory data) private {
        (bool ok, bytes memory result) = token.call(data);
        if (!ok || (result.length != 0 && !abi.decode(result, (bool)))) {
            revert TokenTransferFailed();
        }
    }
}

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
    function approve(address, uint256) external returns (bool);
}

interface IERC1271 {
    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4);
}

interface IV2Pair {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112, uint112, uint32);
    function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external;
}

interface IV3Pool {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

interface IAlgebraPool {
    function swap(
        address recipient,
        bool zeroToOne,
        int256 amountRequired,
        uint160 limitSqrtPrice,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);
}

interface IBalancerVault {
    struct SingleSwap {
        bytes32 poolId;
        uint8 kind;
        address assetIn;
        address assetOut;
        uint256 amount;
        bytes userData;
    }

    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }

    function swap(
        SingleSwap calldata singleSwap,
        FundManagement calldata funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256 amountCalculated);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.