Skip to content
Verified contractExactApache-2.0-or-later

A0xRouter

Address0x8e0f4cb68e276e31cf48b33eddd40325f5a736d2
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
Apache-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,096,012
Creation transaction
0xc9416b04ee…114fc5f860

29 files

project/contracts/protocol/extensions/adapters/A0xRouter.sol

// SPDX-License-Identifier: Apache-2.0-or-later
// solhint-disable-next-line
pragma solidity 0.8.37;

import {EnumerableSet, AddressSet} from "../../libraries/EnumerableSet.sol";
import {ReentrancyGuardTransient} from "../../libraries/ReentrancyGuardTransient.sol";
import {SafeTransferLib} from "../../libraries/SafeTransferLib.sol";
import {StorageLib} from "../../libraries/StorageLib.sol";
import {IEOracle} from "./interfaces/IEOracle.sol";
import {IMinimumVersion} from "./interfaces/IMinimumVersion.sol";
import {IA0xRouter} from "./interfaces/IA0xRouter.sol";

import {ISettlerActions} from "0x-settler/src/ISettlerActions.sol";
import {IAllowanceHolder} from "0x-settler/src/allowanceholder/IAllowanceHolder.sol";
import {ISettlerTakerSubmitted} from "0x-settler/src/interfaces/ISettlerTakerSubmitted.sol";
import {IDeployer} from "0x-settler/src/deployer/IDeployer.sol";
import {Feature} from "0x-settler/src/deployer/Feature.sol";

/// @title A0xRouter - Allows smart pool swaps via the 0x swap aggregator.
/// @author Gabriele Rigo - <[email protected]>
/// @dev See docs/0x/ACTION_ALLOWLIST.md for the validation model and security rationale.
contract A0xRouter is IA0xRouter, IMinimumVersion, ReentrancyGuardTransient {
    using EnumerableSet for AddressSet;
    using SafeTransferLib for address;

    string private constant _REQUIRED_VERSION = "4.0.0";

    /// @dev Sentinel address defined in 0x SettlerAbstract.ETH_ADDRESS for native currency.
    address private constant _ETH_SENTINEL = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    address private immutable _adapter;
    IAllowanceHolder private immutable _allowanceHolder;
    IDeployer private immutable _deployer;

    /// @dev Feature 2 = Taker Submitted (same-chain swaps). Not importable from settler.
    Feature private constant _TAKER_SUBMITTED_FEATURE = Feature.wrap(2);

    /// @param allowanceHolder The 0x AllowanceHolder contract address (chain-specific, immutable).
    /// @param deployer The 0x Deployer/Registry contract address (same on all chains).
    constructor(address allowanceHolder, address deployer) {
        _adapter = address(this);
        _allowanceHolder = IAllowanceHolder(allowanceHolder);
        _deployer = IDeployer(deployer);
    }

    modifier onlyDelegateCall() {
        require(address(this) != _adapter, DirectCallNotAllowed());
        _;
    }

    /// @inheritdoc IMinimumVersion
    function requiredVersion() external pure override returns (string memory) {
        return _REQUIRED_VERSION;
    }

    /// @inheritdoc IA0xRouter
    function exec(
        address operator,
        address token,
        uint256 amount,
        address payable target,
        bytes calldata data
    ) external payable override nonReentrant onlyDelegateCall returns (bytes memory) {
        _requireGenuineSettler(target);
        require(operator == target, OperatorMustEqualTarget());
        _validateSettlerCalldata(target, data);

        bool isNativeETH = token.isAddressZero() || token == _ETH_SENTINEL;
        uint256 value = isNativeETH ? amount : 0;

        // Approve max before call — ERC20 skips allowance deduction at type(uint256).max.
        if (!isNativeETH) {
            token.safeApprove(address(_allowanceHolder), type(uint256).max);
        }

        try _allowanceHolder.exec{value: value}(operator, token, amount, target, data) returns (bytes memory result) {
            // Reset to 1 after success — no hanging approvals, slot stays warm.
            if (!isNativeETH) {
                token.safeApprove(address(_allowanceHolder), 1);
            }
            return result;
        } catch Error(string memory reason) {
            revert(reason);
        } catch (bytes memory returnData) {
            if (value > address(this).balance) {
                revert InsufficientNativeBalance();
            }
            assembly {
                revert(add(returnData, 32), mload(returnData))
            }
        }
    }

    /// @dev Adds buyToken to active tokens if it has a valid price feed.
    ///  Maps the 0x ETH sentinel (0xEeee...) to address(0) because the EOracle recognizes
    ///  address(0) and wrappedNative as having price feeds, but not the sentinel.
    function _assertTokenOutHasPriceFeed(address buyToken) private {
        if (buyToken == _ETH_SENTINEL) {
            buyToken = address(0);
        }
        AddressSet storage values = StorageLib.activeTokensSet();
        values.addUnique(IEOracle(address(this)), buyToken, StorageLib.pool().baseToken);
    }

    /// @dev Iterates settler actions and enforces the adapter's own invariants. Action
    ///  selectors are intentionally not filtered: the pool operator is responsible for
    ///  calldata correctness (see docs/0x/ACTION_ALLOWLIST.md), and filtering would make
    ///  the adapter fragile to 0x settler upgrades.
    function _checkActionsAllowed(address target, bytes calldata data) private pure {
        // ABI layout: data[100:132] = offset to actions[] (4th word after selector).
        uint256 actionsOffset = abi.decode(data[100:132], (uint256));
        uint256 arrStart = 4 + actionsOffset;
        uint256 numActions = abi.decode(data[arrStart:arrStart + 32], (uint256));

        for (uint256 i; i < numActions; ++i) {
            uint256 elPos = arrStart + 32 + i * 32;
            uint256 elOffset = abi.decode(data[elPos:elPos + 32], (uint256));
            uint256 selectorPos = arrStart + elOffset + 64;
            bytes4 actionSelector = bytes4(data[selectorPos:selectorPos + 4]);

            // TRANSFER_FROM routes sell tokens from the pool into the Settler for internal routing.
            if (actionSelector == ISettlerActions.TRANSFER_FROM.selector) {
                address transferFromRecipient = abi.decode(data[selectorPos + 4:selectorPos + 36], (address));
                require(transferFromRecipient == target, TransferFromRecipientNotSettler(transferFromRecipient));
            }
        }
    }

    /// @dev Verifies target is current or previous Feature 2 settler via the Deployer registry.
    function _requireGenuineSettler(address target) private view {
        require(
            _deployer.ownerOf(Feature.unwrap(_TAKER_SUBMITTED_FEATURE)) == target ||
                _deployer.prev(_TAKER_SUBMITTED_FEATURE) == target,
            CounterfeitSettler(target)
        );
    }

    /// @dev Validates settler calldata: correct selector, recipient, price feed, and action invariants.
    function _validateSettlerCalldata(address target, bytes calldata data) private {
        require(data.length >= 164, InvalidSettlerCalldata());

        require(bytes4(data[:4]) == ISettlerTakerSubmitted.execute.selector, UnsupportedSettlerFunction());

        (address recipient, address buyToken) = abi.decode(data[4:68], (address, address));
        require(recipient == address(this), RecipientNotSmartPool());

        _assertTokenOutHasPriceFeed(buyToken);
        _checkActionsAllowed(target, data);
    }
}

project/contracts/protocol/extensions/adapters/interfaces/IA0xRouter.sol

// SPDX-License-Identifier: Apache 2.0
pragma solidity >=0.8.0 <0.9.0;

/// @title IA0xRouter - Interface for the 0x swap aggregator adapter.
/// @notice Allows Rigoblock smart pools to execute swaps via the 0x AllowanceHolder and Settler contracts.
/// @author Gabriele Rigo - <[email protected]>
interface IA0xRouter {
    /// @notice Thrown when a call is made directly to the adapter instead of via delegatecall.
    error DirectCallNotAllowed();

    /// @notice Thrown when the swap recipient is not the smart pool.
    error RecipientNotSmartPool();

    /// @notice Thrown when the target is not a genuine 0x Settler instance.
    error CounterfeitSettler(address target);

    /// @notice Thrown when the Settler calldata has an unsupported function selector.
    error UnsupportedSettlerFunction();

    /// @notice Thrown when the Settler calldata is too short to decode.
    error InvalidSettlerCalldata();

    /// @notice Thrown when the pool does not hold enough native balance.
    error InsufficientNativeBalance();

    /// @notice Thrown when operator is not the same address as target.
    /// @dev AllowanceHolder stores the ephemeral allowance under `operator`. If operator differs
    ///  from the genuine Settler (target), a malicious operator contract could consume the
    ///  ephemeral allowance and drain pool tokens to an arbitrary address.
    error OperatorMustEqualTarget();

    /// @notice Thrown when a TRANSFER_FROM action's recipient is not the Settler itself.
    /// @dev Allowing an arbitrary recipient would let the pool owner drain funds.
    /// @param recipient The decoded recipient address that failed the check.
    error TransferFromRecipientNotSettler(address recipient);

    /// @notice Execute a swap via the 0x AllowanceHolder contract.
    /// @dev The calldata is forwarded unmodified to AllowanceHolder after validation.
    /// @param operator The address authorized to consume the ephemeral allowance. Must equal `target`.
    /// @param token The sell token address.
    /// @param amount The sell token amount.
    /// @param target The 0x Settler contract address that will execute the swap.
    /// @param data The Settler.execute() calldata containing swap instructions.
    /// @return result The return data from AllowanceHolder.exec.
    function exec(
        address operator,
        address token,
        uint256 amount,
        address payable target,
        bytes calldata data
    ) external payable returns (bytes memory result);
}

project/contracts/protocol/extensions/adapters/interfaces/IEOracle.sol

// SPDX-License-Identifier: Apache-2.0-or-later
pragma solidity >=0.8.0 <0.9.0;

interface IEOracle {
    /// @notice Returns the sum of the token amounts converted to a target token.
    /// @dev Will first try to convert via cross with chain currency, fallback to direct cross if not available.
    /// @param tokens The array of token addresses to be converted.
    /// @param amounts The array of amounts to be converted.
    /// @param targetToken The address of the target token.
    /// @return totalConvertedAmount The total value of converted amount in target token amount.
    function convertBatchTokenAmounts(
        address[] calldata tokens,
        int256[] calldata amounts,
        address targetToken
    ) external view returns (int256 totalConvertedAmount);

    /// @notice Returns a token amount converted to a target token.
    /// @dev Will first try to convert via cross with chain currency, fallback to direct cross if not available.
    /// @param token The address of the token to be converted.
    /// @param amount The amount to be converted.
    /// @param targetToken The address of the target token.
    /// @return convertedAmount The value of converted amount in target token amount.
    function convertTokenAmount(
        address token,
        int256 amount,
        address targetToken
    ) external view returns (int256 convertedAmount);

    /// @notice Returns whether a token has a price feed.
    /// @param token The address of the token.
    /// @return Boolean the price feed exists.
    function hasPriceFeed(address token) external view returns (bool);

    /// @notice Returns token price aginst native currency.
    /// @param token The address of the token.
    /// @return twap The time weighted average price.
    function getTwap(address token) external view returns (int24 twap);
}

project/contracts/protocol/extensions/adapters/interfaces/IMinimumVersion.sol

// SPDX-License-Identifier: Apache 2.0
pragma solidity >=0.8.0 <0.9.0;

interface IMinimumVersion {
    /// @notice Returns the minimum implementation version to use an external application.
    /// @dev Adapters must implement it when modifying proxy state or storage.
    /// @return String of the minimum supported version.
    function requiredVersion() external view returns (string memory);
}

project/contracts/protocol/interfaces/IERC20.sol

// SPDX-License-Identifier: Apache 2.0
/*

 Copyright 2018 RigoBlock, Rigo Investment Sagl.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

*/

pragma solidity >=0.8.0 <0.9.0;

interface IERC20 {
    /// @notice Emitted when a token is transferred.
    /// @param from Address transferring the tokens.
    /// @param to Address receiving the tokens.
    /// @param value Number of token units.
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Emitted when a token holder sets and approval.
    /// @param owner Address of the account setting the approval.
    /// @param spender Address of the allowed account.
    /// @param value Number of approved units.
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /// @notice Transfers token from holder to another address.
    /// @param to Address to send tokens to.
    /// @param value Number of token units to send.
    /// @return success Bool the transaction was successful.
    function transfer(address to, uint256 value) external returns (bool success);

    /// @notice Allows spender to transfer tokens from the holder.
    /// @param from Address of the token holder.
    /// @param to Address to send tokens to.
    /// @param value Number of units to transfer.
    /// @return success Bool the transaction was successful.
    function transferFrom(
        address from,
        address to,
        uint256 value
    ) external returns (bool success);

    /// @notice Allows a holder to approve a spender.
    /// @param spender Address of the token spender.
    /// @param value Number of units to be approved.
    /// @return success Bool the transaction was successful.
    function approve(address spender, uint256 value) external returns (bool success);

    /// @notice Returns token balance for an address.
    /// @param who Address to query balance for.
    /// @return Number of units held.
    function balanceOf(address who) external view returns (uint256);

    /// @notice Returns token allowance of an address to another address.
    /// @param owner Address of token hodler.
    /// @param spender Address of the token spender.
    /// @return Number of allowed units.
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Returns token decimals.
    /// @return Uint8 number of decimals.
    function decimals() external view returns (uint8);
}

project/contracts/protocol/interfaces/v4/pool/ISmartPoolEvents.sol

// SPDX-License-Identifier: Apache 2.0-or-later
pragma solidity >=0.8.0 <0.9.0;

/// @title Rigoblock V3 Pool Events - Declares events of the pool contract.
/// @author Gabriele Rigo - <[email protected]>
interface ISmartPoolEvents {
    /// @notice Emitted when a new pool is initialized.
    /// @dev Pool is initialized at new pool creation.
    /// @param group Address of the factory.
    /// @param owner Address of the owner.
    /// @param baseToken Address of the base token.
    /// @param name String name of the pool.
    /// @param symbol String symbol of the pool.
    event PoolInitialized(
        address indexed group,
        address indexed owner,
        address indexed baseToken,
        string name,
        bytes8 symbol
    );

    /// @notice Emitted when new owner is set.
    /// @param old Address of the previous owner.
    /// @param current Address of the new owner.
    event NewOwner(address indexed old, address indexed current);

    /// @notice Emitted when pool tokens are minted or burned.
    /// @dev Shares are non-transferable: this event is only emitted by mint/burn flows.
    /// @param from Address sending to the pool or burning from.
    /// @param to Address receiving from the pool or burning to.
    /// @param value Number of pool token units.
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Emitted when NAV storage is updated.
    /// @param sender Address of the wallet prompting an update.
    /// @param pool Address of the pool.
    /// @param unitaryValue Value of 1 token in wei units.
    event NewNav(address indexed sender, address indexed pool, uint256 unitaryValue);

    /// @notice Emitted when pool operator sets new mint fee.
    /// @param pool Address of the pool.
    /// @param who Address that is sending the transaction.
    /// @param transactionFee Number of the new fee in wei.
    event NewFee(address indexed pool, address indexed who, uint16 transactionFee);

    /// @notice Emitted when pool operator updates fee collector address.
    /// @param pool Address of the pool.
    /// @param who Address that is sending the transaction.
    /// @param feeCollector Address of the new fee collector.
    event NewCollector(address indexed pool, address indexed who, address feeCollector);

    /// @notice Emitted when pool operator updates minimum holding period.
    /// @param pool Address of the pool.
    /// @param minimumPeriod Number of seconds.
    event MinimumPeriodChanged(address indexed pool, uint48 minimumPeriod);

    /// @notice Emitted when pool operator updates the mint/burn spread.
    /// @param pool Address of the pool.
    /// @param spread Number of the spread in basis points.
    event SpreadChanged(address indexed pool, uint16 spread);

    /// @notice Emitted when pool operator sets a kyc provider.
    /// @param pool Address of the pool.
    /// @param kycProvider Address of the kyc provider.
    event KycProviderSet(address indexed pool, address indexed kycProvider);

    /// @notice Emitted when a user sets an operator.
    /// @param holder Address of the user.
    /// @param operator Address of the operator.
    /// @param approved Boolean the operator is approved by the user.
    event OperatorSet(address indexed holder, address indexed operator, bool approved);

    /// @notice Emitted when a selector delegation is added or removed by the pool owner.
    /// @param pool Address of the pool.
    /// @param delegated Address whose delegation status changed.
    /// @param selector Function selector whose access was updated.
    /// @param isDelegated True if access was granted, false if revoked.
    event DelegationUpdated(address indexed pool, address indexed delegated, bytes4 indexed selector, bool isDelegated);

    /// @notice Emitted when a token's active status changes in the pool.
    /// @param token Address of the token whose status changed.
    /// @param isActive True if token was activated, false if deactivated.
    event TokenStatusChanged(address indexed token, bool isActive);
}

project/contracts/protocol/libraries/ApplicationsLib.sol

// SPDX-License-Identifier: Apache-2.0-or-later
pragma solidity ^0.8.4;

import {Applications} from "../types/Applications.sol";

struct ApplicationsSlot {
    uint256 packedApplications;
}

library ApplicationsLib {
    error ApplicationIndexBitmaskRange();

    uint256 private constant MAX_ALLOWED_APPLICATIONS = 255;

    /// @notice Sets an application as active in the bitmask.
    /// @param self The storage slot where the packed applications are stored.
    /// @param appIndex The application to set as active.
    function storeApplication(ApplicationsSlot storage self, uint256 appIndex) internal {
        require(appIndex < MAX_ALLOWED_APPLICATIONS, ApplicationIndexBitmaskRange());
        uint256 flag = 1 << appIndex;
        self.packedApplications |= flag;
    }

    /// @notice Removes an application from being active in the bitmask.
    /// @param self The storage slot where the packed applications are stored.
    /// @param appIndex The application to remove.
    function removeApplication(ApplicationsSlot storage self, uint256 appIndex) internal {
        require(appIndex < MAX_ALLOWED_APPLICATIONS, ApplicationIndexBitmaskRange());
        uint256 flag = ~(1 << appIndex);
        self.packedApplications &= flag;
    }

    /// @notice Checks if an application is active in the bitmask.
    /// @param packedApplications The bitmap packed active applications flags.
    /// @param appIndex The application to check.
    /// @return bool Whether the application is active.
    function isActiveApplication(uint256 packedApplications, uint256 appIndex) internal pure returns (bool) {
        require(appIndex < MAX_ALLOWED_APPLICATIONS, ApplicationIndexBitmaskRange());
        uint256 flag = 1 << appIndex;
        return (packedApplications & flag) != 0;
    }

    /// @notice Returns whether an application should be queried for token balances.
    /// @dev GRG_STAKING is always queried: it is a pre-existing application that self-activates
    ///  on the first NAV write, so the active-bit may not be set yet on a fresh pool.
    /// @param packedApplications The bitmap packed active applications flags.
    /// @param appIndex The application to check.
    /// @return bool Whether the application should be queried.
    function shouldQueryApp(uint256 packedApplications, uint256 appIndex) internal pure returns (bool) {
        if (Applications(appIndex) == Applications.GRG_STAKING) return true;
        return isActiveApplication(packedApplications, appIndex);
    }
}

project/contracts/protocol/libraries/DelegationLib.sol

// SPDX-License-Identifier: Apache 2.0
pragma solidity ^0.8.18;

/// @notice Per-pool delegated-access state stored at a dedicated ERC-7201 slot.
/// @dev Four parallel data structures maintain two enumerable mappings:
///      selector → [delegated addresses]  (for revoke-by-selector)
///      address  → [delegated selectors]  (for revoke-by-address)
///      Both directions are kept in O(1) via position tracking (1-indexed, 0 = absent).
struct DelegationData {
    /// @dev selector → (address → 1-indexed position in selectorAddresses[selector]). 0 = not delegated.
    mapping(bytes4 selector => mapping(address delegated => uint256 position)) selectorToAddressPosition;
    /// @dev selector → ordered list of delegated addresses.
    mapping(bytes4 selector => address[] addresses) selectorAddresses;
    /// @dev address → ordered list of selectors delegated to it.
    mapping(address delegated => bytes4[] selectors) addressSelectors;
    /// @dev address → (selector → 1-indexed position in addressSelectors[address]). 0 = not present.
    mapping(address delegated => mapping(bytes4 selector => uint256 position)) addressToSelectorPosition;
}

/// @title DelegationLib - Enumerable bi-directional delegation registry.
/// @notice Library for managing granular per-selector delegated write access to pool adapters.
/// @dev All writes maintain two enumerable index structures so callers can enumerate delegations
///      in either direction without iterating unpredictably large arrays.
library DelegationLib {
    // -------------------------------------------------------------------------
    // Mutating operations
    // -------------------------------------------------------------------------

    /// @notice Grants delegated write access to `selector` for `addr`.
    /// @return added True if the pair was newly granted (false = already existed, no storage change).
    function add(DelegationData storage self, bytes4 selector, address addr) internal returns (bool added) {
        if (self.selectorToAddressPosition[selector][addr] != 0) return false;

        // Register in selector → addresses direction
        self.selectorAddresses[selector].push(addr);
        self.selectorToAddressPosition[selector][addr] = self.selectorAddresses[selector].length; // 1-indexed

        // Register in address → selectors direction
        self.addressSelectors[addr].push(selector);
        self.addressToSelectorPosition[addr][selector] = self.addressSelectors[addr].length; // 1-indexed

        return true;
    }

    /// @notice Revokes delegated write access to `selector` for `addr`.
    /// @return removed True if the pair was present and removed (false = was not delegated, no storage change).
    function remove(DelegationData storage self, bytes4 selector, address addr) internal returns (bool removed) {
        uint256 posInSelector = self.selectorToAddressPosition[selector][addr];
        if (posInSelector == 0) return false;

        // Swap-and-pop from selectorAddresses[selector]
        address[] storage addrList = self.selectorAddresses[selector];
        uint256 lastIdx = addrList.length - 1;
        uint256 removeIdx = posInSelector - 1;

        if (removeIdx != lastIdx) {
            address lastAddr = addrList[lastIdx];
            addrList[removeIdx] = lastAddr;
            self.selectorToAddressPosition[selector][lastAddr] = posInSelector;
        }
        addrList.pop();
        delete self.selectorToAddressPosition[selector][addr];

        // Swap-and-pop from addressSelectors[addr]
        uint256 posInAddr = self.addressToSelectorPosition[addr][selector];
        bytes4[] storage selList = self.addressSelectors[addr];
        uint256 lastSel = selList.length - 1;
        uint256 removeSelIdx = posInAddr - 1;

        if (removeSelIdx != lastSel) {
            bytes4 lastSelector = selList[lastSel];
            selList[removeSelIdx] = lastSelector;
            self.addressToSelectorPosition[addr][lastSelector] = posInAddr;
        }
        selList.pop();
        delete self.addressToSelectorPosition[addr][selector];

        return true;
    }

    /// @notice Revokes all delegations previously granted to `addr` (e.g. compromised wallet).
    /// @dev Iterates the (short) list of selectors for addr and cleans up both directions.
    function removeAllByAddress(DelegationData storage self, address addr) internal {
        bytes4[] storage selectors = self.addressSelectors[addr];
        uint256 len = selectors.length;

        for (uint256 i = 0; i < len; ++i) {
            bytes4 sel = selectors[i];

            // Remove addr from selectorAddresses[sel] via swap-and-pop
            uint256 posInSelector = self.selectorToAddressPosition[sel][addr];
            address[] storage addrList = self.selectorAddresses[sel];
            uint256 lastIdx = addrList.length - 1;
            uint256 removeIdx = posInSelector - 1;

            if (removeIdx != lastIdx) {
                address lastAddr = addrList[lastIdx];
                addrList[removeIdx] = lastAddr;
                self.selectorToAddressPosition[sel][lastAddr] = posInSelector;
            }
            addrList.pop();
            delete self.selectorToAddressPosition[sel][addr];
            delete self.addressToSelectorPosition[addr][sel];
        }

        delete self.addressSelectors[addr];
    }

    /// @notice Revokes all delegations for `selector` (e.g. adapter being replaced by governance).
    /// @dev Iterates the (short) list of addresses for selector and cleans up both directions.
    function removeAllBySelector(DelegationData storage self, bytes4 selector) internal {
        address[] storage addrs = self.selectorAddresses[selector];
        uint256 len = addrs.length;

        for (uint256 i = 0; i < len; ++i) {
            address addr = addrs[i];

            // Remove selector from addressSelectors[addr] via swap-and-pop
            uint256 posInAddr = self.addressToSelectorPosition[addr][selector];
            bytes4[] storage selList = self.addressSelectors[addr];
            uint256 lastSel = selList.length - 1;
            uint256 removeSel = posInAddr - 1;

            if (removeSel != lastSel) {
                bytes4 lastSelector = selList[lastSel];
                selList[removeSel] = lastSelector;
                self.addressToSelectorPosition[addr][lastSelector] = posInAddr;
            }
            selList.pop();
            delete self.addressToSelectorPosition[addr][selector];
            delete self.selectorToAddressPosition[selector][addr];
        }

        delete self.selectorAddresses[selector];
    }

    // -------------------------------------------------------------------------
    // View helpers
    // -------------------------------------------------------------------------

    /// @notice Returns all addresses currently delegated for `selector`.
    function getAddresses(DelegationData storage self, bytes4 selector) internal view returns (address[] memory) {
        return self.selectorAddresses[selector];
    }

    /// @notice Returns all selectors currently delegated to `addr`.
    function getSelectors(DelegationData storage self, address addr) internal view returns (bytes4[] memory) {
        return self.addressSelectors[addr];
    }
}

project/contracts/protocol/libraries/EnumerableSet.sol

// SPDX-License-Identifier: Apache 2.0
pragma solidity ^0.8.18;

import {IEOracle} from "../extensions/adapters/interfaces/IEOracle.sol";
import {ISmartPoolEvents} from "../interfaces/v4/pool/ISmartPoolEvents.sol";

struct AddressSet {
    // List of stored addresses
    address[] addresses;
    // Mapping of address to position.
    // Position 0 means an address has never been added before.
    mapping(address token => uint256 position) positions;
}

struct Bytes32Set {
    // List of stored values
    bytes32[] values;
    // Mapping of value to position.
    // Position 0 means a value has never been added before.
    mapping(bytes32 value => uint256 position) positions;
}

/// @notice Pool initialization parameters.
/// @dev This struct is not visible externally and used to store/read pool init params.
/// @param name String of the pool name (max 32 characters).
/// @param symbol Bytes8 of the pool symbol (from 3 to 5 characters).
/// @param decimals Uint8 decimals.
/// @param owner Address of the pool operator.
/// @param unlocked Boolean the pool is locked for reentrancy check.
/// @param baseToken Address of the base token of the pool (0 for base currency).
struct Pool {
    string name;
    bytes8 symbol;
    uint8 decimals;
    address owner;
    bool unlocked;
    address baseToken;
}

/// @notice Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol
library EnumerableSet {
    error AddressListExceedsMaxLength();
    error TokenPriceFeedDoesNotExist(address token);

    // limit size of array to prevent DOS to nav estimates
    uint256 internal constant _MAX_UNIQUE_VALUES = type(uint8).max / 2; // max 128 values

    // flag for removed address
    uint256 private constant REMOVED_ADDRESS_FLAG = type(uint256).max;
    // flag for removed bytes32 value
    uint256 private constant REMOVED_BYTES32_FLAG = type(uint256).max;

    /// @notice Adds `token` to the set if it is not the base token and not already active.
    /// @dev Reads set.positions[token] exactly once. Returns whether the token was active
    ///  before this call (base token is always considered active and is never stored).
    function addUnique(
        AddressSet storage set,
        IEOracle eOracle,
        address token,
        address baseToken
    ) internal returns (bool wasActive) {
        if (token == baseToken) return true;

        uint256 position = set.positions[token]; // single SLOAD
        wasActive = (position != 0 && position != REMOVED_ADDRESS_FLAG);

        if (!wasActive) {
            require(set.addresses.length < _MAX_UNIQUE_VALUES, AddressListExceedsMaxLength());
            require(eOracle.hasPriceFeed(token), TokenPriceFeedDoesNotExist(token));
            set.addresses.push(token);
            set.positions[token] = set.addresses.length;
            emit ISmartPoolEvents.TokenStatusChanged(token, true);
        }
    }

    function remove(AddressSet storage set, address token) internal {
        uint256 position = set.positions[token];

        if (position != 0 && position != REMOVED_ADDRESS_FLAG) {
            // Copy last element at position and pop last element
            uint256 addressIndex = position - 1;
            uint256 lastIndex = set.addresses.length - 1;

            if (addressIndex != lastIndex) {
                address lastAddress = set.addresses[lastIndex];

                // Move the lastToken to the index where the token to delete is
                set.addresses[addressIndex] = lastAddress;
                // Update the tracked position of the lastToken (that was just moved)
                set.positions[lastAddress] = position;
            }

            // Delete the slot where the moved token was stored
            set.addresses.pop();

            // Delete the tracked position for the deleted slot without clearing storage
            set.positions[token] = REMOVED_ADDRESS_FLAG;

            // emit event for token deactivation
            emit ISmartPoolEvents.TokenStatusChanged(token, false);
            return;
        }
    }

    function isActive(AddressSet storage set, address token) internal view returns (bool) {
        uint256 position = set.positions[token];
        return (position != 0 && position != REMOVED_ADDRESS_FLAG);
    }

    function add(Bytes32Set storage set, bytes32 value) internal {
        if (set.positions[value] == 0 || set.positions[value] == REMOVED_BYTES32_FLAG) {
            require(set.values.length < _MAX_UNIQUE_VALUES, AddressListExceedsMaxLength());
            set.values.push(value);
            set.positions[value] = set.values.length;
        }
    }

    function remove(Bytes32Set storage set, bytes32 value) internal {
        uint256 position = set.positions[value];
        if (position != 0 && position != REMOVED_BYTES32_FLAG) {
            uint256 valueIndex = position - 1;
            uint256 lastIndex = set.values.length - 1;
            if (valueIndex != lastIndex) {
                bytes32 lastValue = set.values[lastIndex];
                set.values[valueIndex] = lastValue;
                set.positions[lastValue] = position;
            }
            set.values.pop();
            set.positions[value] = REMOVED_BYTES32_FLAG;
        }
    }

    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        uint256 position = set.positions[value];
        return position != 0 && position != REMOVED_BYTES32_FLAG;
    }

    function length(Bytes32Set storage set) internal view returns (uint256) {
        return set.values.length;
    }

    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return set.values[index];
    }
}

project/contracts/protocol/libraries/ReentrancyGuardTransient.sol

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

pragma solidity ^0.8.24;

import {TransientSlot} from "./TransientSlot.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}

project/contracts/protocol/libraries/SafeTransferLib.sol

// SPDX-License-Identifier: Apache3.0-or-later
pragma solidity ^0.8.11;

import {IERC20} from "../interfaces/IERC20.sol";

type Currency is address;

/// @title SafeTransferLib
/// @dev This library allows for safe transfer of tokens without using assembly
library SafeTransferLib {
    error ApprovalFailed(address token);
    error NativeTransferFailed();
    error TokenTransferFailed();
    error TokenTransferFromFailed();
    error ApprovalTargetIsNotContract(address token);

    function safeTransferNative(address to, uint256 amount) internal {
        (bool success, ) = to.call{gas: 2300, value: amount}("");
        require(success, NativeTransferFailed());
    }

    function safeTransfer(address token, address to, uint256 amount) internal {
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory data) = token.call(abi.encodeCall(IERC20.transfer, (to, amount)));
        require(success && (data.length == 0 || abi.decode(data, (bool))), TokenTransferFailed());
    }

    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory data) = token.call(abi.encodeCall(IERC20.transferFrom, (from, to, amount)));
        require(success && (data.length == 0 || abi.decode(data, (bool))), TokenTransferFromFailed());
    }

    /// @dev Allows approving all ERC20 tokens, forcing approvals when needed.
    function safeApprove(address token, address spender, uint256 amount) internal {
        // token address sanity check
        bool isContract = token.code.length > 0;
        require(isContract, ApprovalTargetIsNotContract(token));
        (bool success, bytes memory data) = token.call(abi.encodeCall(IERC20.approve, (spender, amount)));

        if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
            // force approval
            (success, data) = token.call(abi.encodeCall(IERC20.approve, (spender, 0)));
            (success, data) = token.call(abi.encodeCall(IERC20.approve, (spender, amount)));

            require(success && ((data.length == 0 && isContract) || abi.decode(data, (bool))), ApprovalFailed(token));
        }
    }

    function isAddressZero(address target) internal pure returns (bool) {
        return target == address(0);
    }
}

project/contracts/protocol/libraries/StorageLib.sol

// SPDX-License-Identifier: Apache-2.0-or-later
pragma solidity ^0.8.0;

import {TokenIdsSlot, HyperliquidData} from "../types/Applications.sol";
import {ApplicationsSlot} from "./ApplicationsLib.sol";
import {DelegationData} from "./DelegationLib.sol";
import {AddressSet, EnumerableSet, Pool} from "./EnumerableSet.sol";

/// @notice A library for extensions to access proxy pre-assigned storage slots.
library StorageLib {
    using EnumerableSet for AddressSet;

    /// @notice persistent storage slots, used to read from proxy storage without having to update implementation
    bytes32 public constant APPLICATIONS_SLOT = 0xdc487a67cca3fd0341a90d1b8834103014d2a61e6a212e57883f8680b8f9c831;
    bytes32 public constant DELEGATION_SLOT = 0x1de728329845ca9693f4e251833e4fd20a461e4f39179bee6e55171aedb6dc19;
    bytes32 public constant POOL_INIT_SLOT = 0xe48b9bb119adfc3bccddcc581484cc6725fe8d292ebfcec7d67b1f93138d8bd8;
    bytes32 public constant POOL_TOKENS_SLOT = 0xf46fb7ff9ff9a406787c810524417c818e45ab2f1997f38c2555c845d23bb9f6;
    bytes32 public constant TOKEN_REGISTRY_SLOT = 0x3dcde6752c7421366e48f002bbf8d6493462e0e43af349bebb99f0470a12300d;
    bytes32 public constant UNIV4_TOKEN_IDS_SLOT = 0xd87266b00c1e82928c0b0200ad56e2ee648a35d4e9b273d2ac9533471e3b5d3c;
    bytes32 public constant HYPERLIQUID_DATA_SLOT = 0x4afbc3162e1589b633acdf6b7c00223a8c67447dd0ad462eaa13272955dff2a1;

    function pool() internal pure returns (Pool storage s) {
        assembly {
            s.slot := POOL_INIT_SLOT
        }
    }

    function delegation() internal pure returns (DelegationData storage s) {
        assembly {
            s.slot := DELEGATION_SLOT
        }
    }

    function activeTokensSet() internal pure returns (AddressSet storage s) {
        assembly {
            s.slot := TOKEN_REGISTRY_SLOT
        }
    }

    function uniV4TokenIdsSlot() internal pure returns (TokenIdsSlot storage s) {
        assembly {
            s.slot := UNIV4_TOKEN_IDS_SLOT
        }
    }

    function activeApplications() internal pure returns (ApplicationsSlot storage s) {
        assembly {
            s.slot := APPLICATIONS_SLOT
        }
    }

    function hyperliquidData() internal pure returns (HyperliquidData storage s) {
        bytes32 slot = HYPERLIQUID_DATA_SLOT;
        assembly {
            s.slot := slot
        }
    }

    /// @notice Checks if a token is owned by the pool (base token or active token)
    /// @param token Token address to check
    /// @return True if token is base token or in active tokens set
    function isOwnedToken(address token) internal view returns (bool) {
        address baseToken = pool().baseToken;

        // Base token is always owned
        if (token == baseToken) {
            return true;
        }

        // Check if token is in active tokens set
        return activeTokensSet().isActive(token);
    }
}

project/contracts/protocol/libraries/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

project/contracts/protocol/types/Applications.sol

// SPDX-License-Identifier: Apache-2.0-or-later
pragma solidity ^0.8.0;

/// @notice Supported Applications.
/// @dev Preserve order when adding new applications, last one is the counter.
enum Applications {
    GRG_STAKING,
    UNIV4_LIQUIDITY,
    GMX_V2_POSITIONS,
    HYPERLIQUID,
    // append new applications here, up to a total of 255 as a theoretical maximum
    COUNT
}

struct TokenIdsSlot {
    uint256[] tokenIds;
    mapping(uint256 tokenId => uint256 index) positions;
}

/// @notice Packed Hyperliquid in-flight accounting.
/// @dev `lastActionCompositeBlock` stores `(l1BlockNumber << 128) | block.number` so that the
///  in-flight window aligns with HyperCore state updates rather than EVM block production.
/// @dev `lastActionTimestamp` records when any Hyperliquid action was last recorded.
struct HyperliquidData {
    uint256 lastActionCompositeBlock;
    int128 inFlightAmount;
    uint64 pendingSpotSend;
    uint48 lastActionTimestamp;
}

project/lib/0x-settler/lib/forge-std/src/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.2;

interface IERC165 {
    /// @notice Query if a contract implements an interface
    /// @param interfaceID The interface identifier, as specified in ERC-165
    /// @dev Interface identification is specified in ERC-165. This function
    /// uses less than 30,000 gas.
    /// @return `true` if the contract implements `interfaceID` and
    /// `interfaceID` is not 0xffffffff, `false` otherwise
    function supportsInterface(bytes4 interfaceID) external view returns (bool);
}

project/lib/0x-settler/lib/forge-std/src/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.2;

/// @dev Interface of the ERC20 standard as defined in the EIP.
/// @dev This includes the optional name, symbol, and decimals metadata.
interface IERC20 {
    /// @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @dev Emitted when the allowance of a `spender` for an `owner` is set, where `value`
    /// is the new allowance.
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /// @notice Returns the amount of tokens in existence.
    function totalSupply() external view returns (uint256);

    /// @notice Returns the amount of tokens owned by `account`.
    function balanceOf(address account) external view returns (uint256);

    /// @notice Moves `amount` tokens from the caller's account to `to`.
    function transfer(address to, uint256 amount) external returns (bool);

    /// @notice Returns the remaining number of tokens that `spender` is allowed
    /// to spend on behalf of `owner`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
    /// @dev Be aware of front-running risks: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Moves `amount` tokens from `from` to `to` using the allowance mechanism.
    /// `amount` is then deducted from the caller's allowance.
    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    /// @notice Returns the name of the token.
    function name() external view returns (string memory);

    /// @notice Returns the symbol of the token.
    function symbol() external view returns (string memory);

    /// @notice Returns the decimals places of the token.
    function decimals() external view returns (uint8);
}

project/lib/0x-settler/lib/permit2/src/interfaces/IEIP712.sol

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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

project/lib/0x-settler/lib/permit2/src/interfaces/ISignatureTransfer.sol

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

import {IEIP712} from "./IEIP712.sol";

/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
    /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
    /// @param maxAmount The maximum amount a spender can request to transfer
    error InvalidAmount(uint256 maxAmount);

    /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
    /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
    error LengthMismatch();

    /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
    event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);

    /// @notice The token and amount details for a transfer signed in the permit transfer signature
    struct TokenPermissions {
        // ERC20 token address
        address token;
        // the maximum amount that can be spent
        uint256 amount;
    }

    /// @notice The signed permit message for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice Specifies the recipient address and amount for batched transfers.
    /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
    /// @dev Reverts if the requested amount is greater than the permitted signed amount.
    struct SignatureTransferDetails {
        // recipient address
        address to;
        // spender requested amount
        uint256 requestedAmount;
    }

    /// @notice Used to reconstruct the signed permit message for multiple token transfers
    /// @dev Do not need to pass in spender address as it is required that it is msg.sender
    /// @dev Note that a user still signs over a spender address
    struct PermitBatchTransferFrom {
        // the tokens and corresponding amounts permitted for a transfer
        TokenPermissions[] permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
    /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
    /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
    /// @dev It returns a uint256 bitmap
    /// @dev The index, or wordPosition is capped at type(uint248).max
    function nonceBitmap(address, uint256) external view returns (uint256);

    /// @notice Transfers a token using a signed permit message
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers a token using a signed permit message
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Invalidates the bits specified in mask for the bitmap at the word position
    /// @dev The wordPos is maxed at type(uint248).max
    /// @param wordPos A number to index the nonceBitmap at
    /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}

project/lib/0x-settler/src/ISettlerActions.sol

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

import {ISignatureTransfer} from "@permit2/interfaces/ISignatureTransfer.sol";

interface ISettlerActions {
    /// VIP actions should always start with `recipient` address and the `permit` from the taker
    /// followed by all the other parameters to ensure compatibility with `executeWithPermit` entrypoint.
    /// `minBuyAmount`/`amountOutMin` should always be the last parameter.

    /// @dev Transfer funds from msg.sender Permit2.
    function TRANSFER_FROM(address recipient, ISignatureTransfer.PermitTransferFrom memory permit, bytes memory sig)
        external;

    // @dev msgValue is interpreted as an upper bound on the expected msg.value, not as an exact specification
    function NATIVE_CHECK(uint256 deadline, uint256 msgValue) external;

    /// @dev Transfer funds from metatransaction requestor into the Settler contract using Permit2. Only for use in `Settler.executeMetaTxn` where the signature is provided as calldata
    function METATXN_TRANSFER_FROM(address recipient, ISignatureTransfer.PermitTransferFrom memory permit) external;

    /// @dev Settle an RfqOrder between maker and taker transfering funds directly between the parties
    // Post-req: Payout if recipient != taker
    function RFQ_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory takerPermit,
        ISignatureTransfer.PermitTransferFrom memory makerPermit,
        address maker,
        bytes memory makerSig,
        bytes memory takerSig
    ) external;

    /// @dev Settle an RfqOrder between maker and taker transfering funds directly between the parties for the entire amount
    function METATXN_RFQ_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory takerPermit,
        ISignatureTransfer.PermitTransferFrom memory makerPermit,
        address maker,
        bytes memory makerSig
    ) external;

    /// @dev Settle an RfqOrder between Maker and Settler. Transfering funds from the Settler contract to maker.
    /// Retaining funds in the settler contract.
    // Pre-req: Funded
    // Post-req: Payout
    function RFQ(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        address maker,
        bytes memory makerSig,
        address takerToken,
        uint256 maxTakerAmount
    ) external;

    function UNISWAPV4(
        address recipient,
        address sellToken,
        uint256 bps,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;
    function UNISWAPV4_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        bytes memory sig,
        uint256 amountOutMin
    ) external;
    function METATXN_UNISWAPV4_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    function BALANCERV3(
        address recipient,
        address sellToken,
        uint256 bps,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;
    function BALANCERV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        bytes memory sig,
        uint256 amountOutMin
    ) external;
    function METATXN_BALANCERV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    function PANCAKE_INFINITY(
        address recipient,
        address sellToken,
        uint256 bps,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;
    function PANCAKE_INFINITY_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        bytes memory sig,
        uint256 amountOutMin
    ) external;
    function METATXN_PANCAKE_INFINITY_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    /// @dev Trades against UniswapV3 using the contracts balance for funding
    // Pre-req: Funded
    // Post-req: Payout
    function UNISWAPV3(address recipient, uint256 bps, bytes memory path, uint256 amountOutMin) external;
    /// @dev Trades against UniswapV3 using user funds via Permit2 for funding
    function UNISWAPV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bytes memory path,
        bytes memory sig,
        uint256 amountOutMin
    ) external;
    /// @dev Trades against UniswapV3 using user funds via Permit2 for funding. Metatransaction variant. Signature is over all actions.
    function METATXN_UNISWAPV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bytes memory path,
        uint256 amountOutMin
    ) external;

    function MAKERPSM(address recipient, uint256 bps, bool buyGem, uint256 amountOutMin, address psm, address dai)
        external;

    function CURVE_TRICRYPTO_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        uint80 poolInfo,
        bytes memory sig,
        uint256 minBuyAmount
    ) external;
    function METATXN_CURVE_TRICRYPTO_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        uint80 poolInfo,
        uint256 minBuyAmount
    ) external;

    function DODOV1(address sellToken, uint256 bps, address pool, bool quoteForBase, uint256 minBuyAmount) external;
    function DODOV2(
        address recipient,
        address sellToken,
        uint256 bps,
        address pool,
        bool quoteForBase,
        uint256 minBuyAmount
    ) external;

    function VELODROME(address recipient, uint256 bps, address pool, uint24 swapInfo, uint256 minBuyAmount) external;

    /// @dev Trades against MaverickV2 using the contracts balance for funding
    /// This action does not use the MaverickV2 callback, so it takes an arbitrary pool address to make calls against.
    /// Passing `tokenAIn` as a parameter actually saves gas relative to introspecting the pool's `tokenA()` accessor.
    function MAVERICKV2(
        address recipient,
        address sellToken,
        uint256 bps,
        address pool,
        bool tokenAIn,
        int32 tickLimit,
        uint256 minBuyAmount
    ) external;

    /// @dev Trades against UniswapV2 using the contracts balance for funding
    /// @param swapInfo is encoded as the upper 16 bits as the fee of the pool in bps, the second
    ///                 lowest bit as "sell token has transfer fee", and the lowest bit as the
    ///                 "token0 for token1" flag.
    function UNISWAPV2(
        address recipient,
        address sellToken,
        uint256 bps,
        address pool,
        uint24 swapInfo,
        uint256 amountOutMin
    ) external;

    function POSITIVE_SLIPPAGE(address payable recipient, address token, uint256 expectedAmount, uint256 maxBps)
        external;

    /// @dev Trades against a basic AMM which follows the approval, transferFrom(msg.sender) interaction
    // Pre-req: Funded
    // Post-req: Payout
    function BASIC(address sellToken, uint256 bps, address pool, uint256 offset, bytes calldata data) external;

    function EKUBO(
        address recipient,
        address sellToken,
        uint256 bps,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    function EKUBOV3(
        address recipient,
        address sellToken,
        uint256 bps,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    function EKUBOV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        bytes memory sig,
        uint256 amountOutMin
    ) external;

    function METATXN_EKUBOV3_VIP(
        address recipient,
        ISignatureTransfer.PermitTransferFrom memory permit,
        bool feeOnTransfer,
        uint256 hashMul,
        uint256 hashMod,
        bytes memory fills,
        uint256 amountOutMin
    ) external;

    function EULERSWAP(
        address recipient,
        address sellToken,
        uint256 bps,
        address pool,
        bool zeroForOne,
        uint256 amountOutMin
    ) external;

    function RENEGADE(address target, address sellToken, bool baseForQuote, bytes memory data, uint256 minBuyAmount)
        external;

    struct BebopMakerSignature {
        bytes signatureBytes;
        uint256 flags;
    }

    struct BebopOrder {
        uint256 expiry;
        address maker_address;
        uint256 maker_nonce;
        address maker_token;
        uint256 taker_amount;
        uint256 maker_amount;

        // the high 5 bits are unused
        // the next 3 bits are the `takerHasNative`, `makerHasNative`, and
        //   `takerUsingPermit2` flags (in that order from high to low) from the
        //   original `packed_commands` field
        // the next 120 bits are unused
        // the low 128 bits are the `event_id` from the original `flags` field
        uint256 event_id_and_flags;
    }

    function BEBOP(
        address recipient,
        address sellToken,
        BebopOrder memory order,
        BebopMakerSignature memory makerSignature,
        uint256 amountOutMin
    ) external;

    function HANJI(
        address sellToken,
        uint256 bps,
        address pool,
        uint256 sellScalingFactor,
        uint256 buyScalingFactor,
        bool isAsk,
        uint256 priceLimit,
        uint256 minBuyAmount
    ) external;

    function CHECK_SLIPPAGE(bool transferExactLimit) external;
}

project/lib/0x-settler/src/allowanceholder/IAllowanceHolder.sol

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

IAllowanceHolder constant ALLOWANCE_HOLDER = IAllowanceHolder(0x0000000000001fF3684f28c67538d4D072C22734);

interface IAllowanceHolder {
    /// @notice Executes against `target` with the `data` payload. Prior to execution, token permits
    ///         are temporarily stored for the duration of the transaction. These permits can be
    ///         consumed by the `operator` during the execution
    /// @notice `operator` consumes the funds during its operations by calling back into
    ///         `AllowanceHolder` with `transferFrom`, consuming a token permit.
    /// @dev Neither `exec` nor `transferFrom` check that `token` contains code.
    /// @dev msg.sender is forwarded to target appended to the msg data (similar to ERC-2771)
    /// @param operator An address which is allowed to consume the token permits
    /// @param token The ERC20 token the caller has authorised to be consumed
    /// @param amount The quantity of `token` the caller has authorised to be consumed
    /// @param target A contract to execute operations with `data`
    /// @param data The data to forward to `target`
    /// @return result The returndata from calling `target` with `data`
    /// @notice If calling `target` with `data` reverts, the revert is propagated
    function exec(address operator, address token, uint256 amount, address payable target, bytes calldata data)
        external
        payable
        returns (bytes memory result);

    /// @notice The counterpart to `exec` which allows for the consumption of token permits later
    ///         during execution
    /// @dev *DOES NOT* check that `token` contains code. This function vacuously succeeds if
    ///      `token` is empty.
    /// @dev can only be called by the `operator` previously registered in `exec`
    /// @param token The ERC20 token to transfer
    /// @param owner The owner of tokens to transfer
    /// @param recipient The destination/beneficiary of the ERC20 `transferFrom`
    /// @param amount The quantity of `token` to transfer`
    /// @return true
    function transferFrom(address token, address owner, address recipient, uint256 amount) external returns (bool);
}

project/lib/0x-settler/src/deployer/Feature.sol

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

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

type Feature is uint128;

function Feature_eq(Feature a, Feature b) pure returns (bool) {
    return Feature.unwrap(a) == Feature.unwrap(b);
}

function isNull(Feature a) pure returns (bool) {
    return Feature.unwrap(a) == 0;
}

using {Feature_eq as ==, isNull} for Feature global;

function wrap(uint256 x) pure returns (Feature) {
    if (x > type(uint128).max) {
        Panic.panic(Panic.ARITHMETIC_OVERFLOW);
    }
    if (x == 0) {
        Panic.panic(Panic.ENUM_CAST);
    }
    return Feature.wrap(uint128(x));
}

project/lib/0x-settler/src/deployer/IDeployer.sol

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

import {IERC165} from "@forge-std/interfaces/IERC165.sol";
import {IOwnable} from "../interfaces/IOwnable.sol";
import {IERC1967Proxy} from "../interfaces/IERC1967Proxy.sol";
import {IMultiCall} from "../interfaces/IMultiCall.sol";
import {Feature} from "./Feature.sol";
import {Nonce} from "./Nonce.sol";

interface IERC721View is IERC165 {
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
    event PermanentURI(string, uint256 indexed); // not technically part of the standard

    function balanceOf(address) external view returns (uint256);
    function ownerOf(uint256 tokenId) external view returns (address);
    function getApproved(uint256 tokenId) external view returns (address);
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

interface IERC721ViewMetadata is IERC721View {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function tokenURI(uint256) external view returns (string memory);
}

interface IDeployerRemove {
    function remove(Feature, Nonce) external returns (bool);
    function remove(address) external returns (bool);
    function removeAll(Feature) external returns (bool);
}

interface IDeployer is IOwnable, IERC721ViewMetadata, IMultiCall, IDeployerRemove {
    function authorized(Feature) external view returns (address, uint40);
    function descriptionHash(Feature) external view returns (bytes32);
    function prev(Feature) external view returns (address);
    function next(Feature) external view returns (address);
    function deployInfo(address) external view returns (Feature, Nonce);
    function authorize(Feature, address, uint40) external returns (bool);
    function setDescription(Feature, string calldata) external returns (string memory);
    function deploy(Feature, bytes calldata) external payable returns (address, Nonce);

    // ERC-6093 errors
    error ERC721InvalidOwner(address owner);
    error ERC721NonexistentToken(uint256 tokenId);

    error FeatureNotInitialized(Feature);
    error FeatureInitialized(Feature);
    error DeployFailed(Feature, Nonce, address);
    error FutureNonce(Nonce);
    error NoInstance();

    event Authorized(Feature indexed, address indexed, uint40);
    event Deployed(Feature indexed, Nonce indexed, address indexed);
    event Removed(Feature indexed, Nonce indexed, address indexed);
    event RemovedAll(Feature indexed);
}

project/lib/0x-settler/src/deployer/Nonce.sol

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

/// @dev if you update this, you also have to update the length of the array `NonceList.List.links` in Deployer.sol
type Nonce is uint32;

function incr(Nonce a) pure returns (Nonce) {
    return Nonce.wrap(Nonce.unwrap(a) + 1);
}

function Nonce_gt(Nonce a, Nonce b) pure returns (bool) {
    return Nonce.unwrap(a) > Nonce.unwrap(b);
}

function Nonce_eq(Nonce a, Nonce b) pure returns (bool) {
    return Nonce.unwrap(a) == Nonce.unwrap(b);
}

function isNull(Nonce a) pure returns (bool) {
    return Nonce.unwrap(a) == 0;
}

using {incr, Nonce_gt as >, Nonce_eq as ==, isNull} for Nonce global;

Nonce constant zero = Nonce.wrap(0);

project/lib/0x-settler/src/interfaces/IERC1967Proxy.sol

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

interface IERC1967Proxy {
    event Upgraded(address indexed implementation);

    function implementation() external view returns (address);

    function version() external view returns (string memory);

    function upgrade(address newImplementation) external payable returns (bool);

    function upgradeAndCall(address newImplementation, bytes calldata data) external payable returns (bool);
}

project/lib/0x-settler/src/interfaces/IMultiCall.sol

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

interface IMultiCall {
    function multicall(bytes[] calldata datas) external;
}

project/lib/0x-settler/src/interfaces/IOwnable.sol

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

import {IERC165} from "@forge-std/interfaces/IERC165.sol";

interface IOwnable is IERC165 {
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    function owner() external view returns (address);

    function transferOwnership(address) external returns (bool);

    error PermissionDenied();
    error ZeroAddress();
}

project/lib/0x-settler/src/interfaces/ISettlerBase.sol

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

import {IERC20} from "@forge-std/interfaces/IERC20.sol";

interface ISettlerBase {
    struct AllowedSlippage {
        address payable recipient;
        IERC20 buyToken;
        uint256 minAmountOut;
    }
}

project/lib/0x-settler/src/interfaces/ISettlerTakerSubmitted.sol

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

import {ISettlerBase} from "./ISettlerBase.sol";

interface ISettlerTakerSubmitted is ISettlerBase {
    function execute(
        AllowedSlippage memory slippage,
        bytes[] calldata actions,
        bytes32 /* zid & affiliate */
    )
        external
        payable
        returns (bool);

    function executeWithPermit(
        AllowedSlippage memory slippage,
        bytes[] calldata actions,
        bytes32 /* zid & affiliate */,
        bytes memory permitData
    ) external payable returns (bool);
}

project/lib/0x-settler/src/utils/Panic.sol

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

library Panic {
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71) // selector for `Panic(uint256)`
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }

    // https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
    uint8 internal constant GENERIC = 0x00;
    uint8 internal constant ASSERT_FAIL = 0x01;
    uint8 internal constant ARITHMETIC_OVERFLOW = 0x11;
    uint8 internal constant DIVISION_BY_ZERO = 0x12;
    uint8 internal constant ENUM_CAST = 0x21;
    uint8 internal constant CORRUPT_STORAGE_ARRAY = 0x22;
    uint8 internal constant POP_EMPTY_ARRAY = 0x31;
    uint8 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    uint8 internal constant OUT_OF_MEMORY = 0x41;
    uint8 internal constant ZERO_FUNCTION_POINTER = 0x51;
}
Compiler settingsShow
{
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "project/:0x-settler/=project/lib/0x-settler/",
    "project/lib/0x-settler/:@forge-std/=project/lib/0x-settler/lib/forge-std/src/",
    "project/lib/0x-settler/:@permit2/=project/lib/0x-settler/lib/permit2/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.