# Conditional Orders

### Conditional Orders Life Cycle

![](https://github.com/Kwenta/smart-margin-v3/blob/main/diagrams/Conditional-Orders.png)

#### Structure

```solidity
    /// "co" == conditional order

    /// @notice order details used to create an
    /// order on a perps market within a co
    struct OrderDetails {
        // order market id
        uint128 marketId;
        // order account id
        uint128 accountId;
        // order size delta (of asset units expressed in
        // decimal 18 digits). It can be positive or negative
        int128 sizeDelta;
        // settlement strategy used for the order
        uint128 settlementStrategyId;
        // acceptable price set at submission
        uint256 acceptablePrice;
        // bool to indicate if the order is reduce only;
        // i.e. it can only reduce the position size
        bool isReduceOnly;
        // tracking code to identify the integrator
        bytes32 trackingCode;
        // address of the referrer
        address referrer;
    }

    /// @notice co
    struct ConditionalOrder {
        // order details
        OrderDetails orderDetails;
        // address of the signer of the order
        address signer;
        // a means to prevent replay attacks and
        // identify the order
        uint256 nonce;
        // option to require all extra conditions
        // to be verified on-chain
        bool requireVerified;
        // address that can execute the order
        // *if* requireVerified is false
        address trustedExecutor;
        // max fee denominated in $sUSD that
        // can be paid to the executor
        uint256 maxExecutorFee;
        // array of extra conditions to be met
        // on-chain *if* requireVerified is true
        bytes[] conditions;
    }
```

#### Off-Chain Submission Process in Smart Margin v3

**Conditional Order Placement**

1. **Order Conditions:** A trader must first define the conditions for the execution of a conditional order.
2. **Verification Choice:** The trader decides if these conditions should be verified on-chain or off-chain.
3. **Setting the Verification Flag:** To make this distinction, the `ConditionalOrder.requireVerified` flag is set to `true` for on-chain verification, or `false` for off-chain.
4. **On-Chain Verification:** If `requireVerified` is `true`, the conditions in `ConditionalOrder.conditions` need to be met on-chain.
5. **Off-Chain Verification:** If `requireVerified` is `false`, the specified conditions in `ConditionalOrder.conditions` will not undergo on-chain verification.
6. **Trusted Executor Assignment:** For off-chain verification (`requireVerified` is `false`), a `ConditionalOrder.trustedExecutor` address must be set, indicating the trusted party for execution.
7. **Role of Trusted Executor:** This executor is the sole entity capable of executing the order when `requireVerified` is `false`, acting on the presumption that off-chain conditions are met.
   * *Note:* The trader relies on the `ConditionalOrder.trustedExecutor` to execute the order only when the off-chain conditions are satisfied.
8. **Fee Specification:** The trader specifies a maximum fee, `ConditionalOrder.maxExecutorFee`, they are willing to pay the executor for successful execution.
9. **Order Signing:** The trader signs the `ConditionalOrder` using their private key.
10. **Order Submission:** The signed `ConditionalOrder` is submitted to Kwenta, or another chosen party, for storage and processing by backend infrastructure.

#### On-Chain Execution Procedure

1. **Account Crediting:** If not done already, the trader credits their account to cover future execution fees. In Synthetix v3 Andromeda, `$USDC` can be converted to `$snxUSD` for credit as demonstrated [here](https://github.com/Kwenta/smart-margin-v3/blob/2cddb99ea81a6463d0be0c4c264b5db6dfbf9b52/test/Credit.t.sol#L59).

#### Execution (Off- and On-Chain)

1. **Condition Monitoring:** Kwenta's backend infrastructure continuously monitors the conditions set in `ConditionalOrder.conditions`.
2. **Execution Initiation:** Upon condition fulfillment, an executor calls `Engine.execute`, submitting the `ConditionalOrder` (`_co`), its signature (`_signature`), and a proposed execution fee (`_fee` in `$snxUSD`).
3. **Execution Validity Checks:** The transaction will fail if the `_fee` exceeds either the `ConditionalOrder.maxExecutorFee` or the account's available credit.
4. **On-Chain Verification for Execution:** If `ConditionalOrder.requireVerified` is `true`, on-chain verification of conditions occurs before execution. This is gas-intensive and therefore expensive.
5. **Executor Flexibility with On-Chain Verification:** Any address can execute the order if `requireVerified` is `true`.
6. **Off-Chain Verification for Execution:** If `requireVerified` is `false`, no on-chain verification occurs before execution, making it less gas-intensive and cheaper.
7. **Executor Restriction with Off-Chain Verification:** The `ConditionalOrder.trustedExecutor` must be the one executing the order if `requireVerified` is `false`.
8. **Execution Requirements:** The `ConditionalOrder` will only be executed if specific criteria are met, including fee limits, account credit, nonce uniqueness, authorized signer, and signature validity.
9. **Order Execution:** If all conditions are satisfied, the `ConditionalOrder` is executed, and the `ConditionalOrder.nonce` is marked as used.

**Credit & Debit Management**

With the integration of Conditional Orders (COs), the Engine contract now manages a credit balance for each account, utilized for executing successful conditional orders. This balance, denominated in `$snxUSD`, is not factored into the account's total margin, ensuring that its debit does not affect open position liquidation risks. Unlike previous versions, the credit in the engine is never locked, as conditional order submission is entirely off-chain, preventing the establishment of a fixed credit balance for outstanding conditional orders.

> refer to this [test suite](https://github.com/Kwenta/smart-margin-v3/blob/main/test/Credit.t.sol) for programmatic examples of managing account credit


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.v3.kwenta.io/infrastructure-overview/conditional-orders.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
