1inch Limit Order Protocol

repository·master·Indexed 43 days ago

https://github.com/1inch/limit-order-protocol

Smart contracts for EVM-based blockchains that enable users to create signed, off-chain limit orders. The protocol supports flexible execution conditions, including partial fills, stop-loss/take-profit, and custom maker interactions. Version 4 introduces enhanced gas efficiency and supports various token standards (ERC20, ERC721, ERC1155) via proxies and extensions. Audited versions include v4.3.2, v4.0.0, v3.0.1, and v2.

Tokens
31.1K
Snippets
141
Records
186
Agent score
55%

What's inside 1inch Limit Order Protocol

  1. What is Permit2Proxy and how does it work?

    master

    Permit2Proxy is a proxy contract designed to enable the use of Uniswap's Permit2 permitTransferFrom within the 1inch Limit Order Protocol. It allows limit orders to use Permit2 assets as maker assets by mimicking the IERC20.transferFrom interface.

    Critical Limitation: Permit2's SignatureTransfer nonces are single-use. Once a nonce is consumed during the first fill, any subsequent attempt at a partial fill will revert. This means orders using this proxy are effectively 'all-or-nothing' regarding the specific nonce used.

  2. What is SafeOrderBuilder and how does it work?

    master

    The SafeOrderBuilder contract is used to build and sign limit orders specifically for a Gnosis Safe.

    To protect against market volatility, the contract uses oracles to automatically adjust the order's taking amount based on the volatility of both the maker and taker assets. Once an order is built, it is signed by the Gnosis Safe and registered within the orderRegistrator.

  3. Use ERC721Proxy for NFT transfers

    master

    The ERC721Proxy is a specialized proxy contract used to facilitate NFT transfers within the protocol. It implements a proxy transfer method designed to mimic the IERC20.transferFrom selector for compatibility, while specifically handling IERC721 tokens.

    Security Note: The amount parameter in the function call is intentionally unused to prevent security vulnerabilities related to partial fills that could lead to unintended ERC-721 token sales.

    // The proxy method signature used for IERC721.transferFrom
    function func_60iHVgK(address from, address to, uint256, uint256 tokenId, contract IERC721 token) external
  4. Structure the args calldata for order fills

    master

    When using fillOrderArgs or fillContractOrderArgs with ARGS_HAS_TARGET set, the args parameter must contain packed calldata. The sequence depends on the takerTraits settings.

    Packed Parameter Order

    1. target (20 bytes): The address to transfer maker funds to (only if ARGS_HAS_TARGET is set).
    2. extension (variable length): The order's extension calldata. The keccak256 hash of this data must match the lower 160 bits of the order's salt.
    3. takerInteraction (variable length): The taker interaction to execute during the fill.

    Note: The lengths of extension and takerInteraction are defined by the ARGS_EXTENSION_LENGTH and ARGS_INTERACTION_LENGTH fields in takerTraits.

  5. How signature validation works for native orders via ERC-1271

    master

    Since proxy contracts do not hold private keys, they use the ERC-1271 standard to validate signatures. When the Limit Order Protocol (LOP) requests a signature validation, the proxy performs the following:

    1. Address Verification: It calculates the expected proxy address from the order hash and checks if it matches the current contract address.
    2. Maker Patching: If the address matches, it patches the order maker to the proxy address.
    3. Hash Verification: It recalculates the order hash and verifies it against the provided signature.
    4. Validation: If all checks pass, it returns the valid signature selector, allowing the order to be processed as if signed by a standard EOA.
  6. Understand the core features of Limit Orders

    master

    The 1inch Limit Order Protocol allows users to create off-chain orders signed via EIP-712 that can be filled on-chain. The protocol is designed for flexibility and gas efficiency.

    Basic Features

    • Asset Control: Select an asset receiver and specify expiration dates.
    • Fill Logic: Choose to allow or disallow partial and multiple fills.
    • Conditional Execution: Define conditions like stop-loss or take-profit.
    • Custom Interactions: Specify arbitrary maker's code to execute before or after filling.
    • Approval Schemes: Support for approve, permit, and permit2 for token spending.
    • WETH Handling: Request WETH unwrapping to ETH before or after a swap.
    • Privacy: Make orders private by restricting them to a specific taker's address.
    • Management: Assign nonces or epochs for easy cancellation.

    Advanced Features

    • Non-ERC20 Support: Use a proxy to handle assets like ERC721 or ERC1155.
    • Dynamic Pricing: Implement on-chain exchange rate calculations for features like Dutch auctions or range orders.
  7. How RemainingInvalidatorLib works

    master

    The RemainingInvalidatorLib provides a mechanism to invalidate orders using the remaining amount of the order as a nonce. This allows for granular invalidation based on how much of an order has been filled.

    Lifecycle of the invalidator:

    • Order Creation: When an order is first created, the remaining invalidator is 0.
    • Order Filling: As an order is filled, the remaining invalidator is updated to the inverse of the remaining amount.

    This mechanism ensures that once an order's remaining amount changes (due to a fill or manual invalidation), the previous state becomes invalid.

  8. Implement the ITakerInteraction callback

    master

    The ITakerInteraction interface provides a callback mechanism used during the order filling lifecycle. This callback is triggered after the maker's funds have been transferred to the taker, but before the taker's funds are transferred to the maker.

    It is designed to allow interactive handling of maker assets to produce taker assets (e.g., interacting with a DEX or a vault).

    Important Limitations:

    • It does not support ETH as taker assets.
    // The order filling lifecycle sequence:
    // preInteraction => Transfer "maker -> taker" => Interaction => Transfer "taker -> maker" => postInteraction
  9. Use the FeeTaker extension for calculating and collecting fees

    master

    The FeeTaker is an extension for the 1inch Limit Order Protocol used to manage fees (integrator and resolver fees) during order execution. It provides methods to calculate the required makingAmount or takingAmount when fees are involved and handles the actual fee collection via postInteraction.

    Data Format for extraData

    Most FeeTaker functions require an extraData byte array. The structure of this array is critical for correct calculations:

    • 2 bytes: Integrator fee percentage (scaled by 1e5)
    • 2 bytes: Resolver fee percentage (scaled by 1e5)
    • 1 byte: Taker whitelist size (N)
    • (bytes10)[N]: Taker whitelist (N entries of 10 bytes each)
    • 20 bytes: Fee recipient (used in postInteraction)
    • 20 bytes: Receiver of taking tokens (optional, used in postInteraction; if omitted, the maker is the receiver)