> ## Documentation Index
> Fetch the complete documentation index at: https://docs.compasslabs.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Unwind a leveraged loop

> Unwind an Aave or Morpho loop in ONE atomic transaction.

Repeatedly withdraws collateral, swaps it to the borrow token at a GUARANTEED
minimum output (enforced on-chain), and repays. The floor discipline means a
swap filling anywhere within the slippage tolerance can never break a later
step; any positive surplus stays in the Credit Account as borrow-token dust
(the preview reports the bound as estimated_max_dust).

Omit target_multiplier for a full close: the debt is cleared exactly —
accrued interest included — and the pair collateral is returned to the Credit
Account. Pass 1 to clear the debt but keep the collateral supplied, or a value
above 1 to delever to that multiplier (it must be below the position's current
multiplier).

Each withdrawal is sized to keep the position's health factor ≥ 1.02 at that
step, so a position opened very close to the liquidation threshold may need
more than one transaction to fully close — set allow_partial=true to return
the maximum single-transaction progress (preview.fully_unwound=false), then
call unloop again to finish. Very large unwinds relative to pool depth can
still exceed the slippage tolerance through their own cumulative price impact.

For protocol=MORPHO pass a market_id from /v2/credit/morpho_markets; inspect
open loops via /v2/credit/looped_positions.



## OpenAPI

````yaml /v2/combined_spec.json post /v2/credit/unloop
openapi: 3.1.0
info:
  title: Compass API
  description: Compass Labs DeFi API
  version: 0.0.1
servers:
  - url: https://api.compasslabs.ai
    description: Production server
security:
  - ApiKeyAuth: []
paths:
  /v2/credit/unloop:
    post:
      tags:
        - Credit
      summary: Unwind a leveraged loop
      description: >-
        Unwind an Aave or Morpho loop in ONE atomic transaction.


        Repeatedly withdraws collateral, swaps it to the borrow token at a
        GUARANTEED

        minimum output (enforced on-chain), and repays. The floor discipline
        means a

        swap filling anywhere within the slippage tolerance can never break a
        later

        step; any positive surplus stays in the Credit Account as borrow-token
        dust

        (the preview reports the bound as estimated_max_dust).


        Omit target_multiplier for a full close: the debt is cleared exactly —

        accrued interest included — and the pair collateral is returned to the
        Credit

        Account. Pass 1 to clear the debt but keep the collateral supplied, or a
        value

        above 1 to delever to that multiplier (it must be below the position's
        current

        multiplier).


        Each withdrawal is sized to keep the position's health factor ≥ 1.02 at
        that

        step, so a position opened very close to the liquidation threshold may
        need

        more than one transaction to fully close — set allow_partial=true to
        return

        the maximum single-transaction progress (preview.fully_unwound=false),
        then

        call unloop again to finish. Very large unwinds relative to pool depth
        can

        still exceed the slippage tolerance through their own cumulative price
        impact.


        For protocol=MORPHO pass a market_id from /v2/credit/morpho_markets;
        inspect

        open loops via /v2/credit/looped_positions.
      operationId: v2_credit_unloop
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreditUnloopRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreditUnloopResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      x-codeSamples:
        - lang: python
          label: Python (SDK)
          source: |-
            from compass_api_sdk import CompassAPI, models


            with CompassAPI(
                api_key_auth="<YOUR_API_KEY_HERE>",
            ) as compass_api:

                res = compass_api.credit.credit_unloop(owner="0x0E407CdeBD8e078E6966ef6740540d25F5897082", chain=models.Chain.ETHEREUM, collateral_token="WETH", borrow_token="USDC", protocol=models.CreditProtocol.AAVE, max_slippage_percent=0.5, allow_partial=False, gas_sponsorship=False)

                # Handle response
                print(res)
        - lang: typescript
          label: Typescript (SDK)
          source: |-
            import { CompassApiSDK } from "@compass-labs/api-sdk";

            const compassApiSDK = new CompassApiSDK({
              apiKeyAuth: "<YOUR_API_KEY_HERE>",
            });

            async function run() {
              const result = await compassApiSDK.credit.creditUnloop({
                owner: "0x0E407CdeBD8e078E6966ef6740540d25F5897082",
                chain: "ethereum",
                protocol: "AAVE",
                collateralToken: "WETH",
                borrowToken: "USDC",
                maxSlippagePercent: 0.5,
                allowPartial: false,
                gasSponsorship: false,
              });

              console.log(result);
            }

            run();
components:
  schemas:
    CreditUnloopRequest:
      properties:
        owner:
          type: string
          title: Owner
          description: The address that owns the Credit Account.
          default: '0x0E407CdeBD8e078E6966ef6740540d25F5897082'
          examples:
            - '0x0E407CdeBD8e078E6966ef6740540d25F5897082'
        chain:
          $ref: '#/components/schemas/Chain'
          description: Blockchain network.
          default: ethereum
          examples:
            - ethereum
        protocol:
          $ref: '#/components/schemas/CreditProtocol'
          description: >-
            Lending protocol to unwind: AAVE or MORPHO. EULER unlooping is not
            available yet.
          default: AAVE
          examples:
            - AAVE
        market_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Market Id
          description: >-
            Morpho only: the bytes32 market id (from /v2/credit/morpho_markets).
            Required when protocol=MORPHO.
        collateral_token:
          type: string
          title: Token
          description: >-
            Token supplied as collateral in the loop being unwound. For MORPHO
            it must be the market's collateral token.
          examples:
            - wstETH
            - WETH
          default: WETH
        borrow_token:
          type: string
          title: Token
          description: >-
            Token borrowed in the loop; withdrawn collateral is swapped back to
            it and used to repay. For MORPHO it must be the market's loan token.
          examples:
            - WETH
            - USDC
          default: USDC
        target_multiplier:
          anyOf:
            - type: number
              minimum: 1
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
            - type: 'null'
          title: Target Multiplier
          description: >-
            Target leverage after the unwind. Omit (null) for a FULL unwind: the
            debt is cleared exactly — accrued interest included — and all pair
            collateral is withdrawn back to the Credit Account. `1` runs the
            same exact debt close but leaves the collateral supplied (earning).
            A value greater than 1 delevers the position to that multiplier.
            Must be below the position's current multiplier.
          examples:
            - 2
            - 1
        max_slippage_percent:
          anyOf:
            - type: number
              maximum: 10
              exclusiveMinimum: 0
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Max Slippage Percent
          description: >-
            Per-swap slippage tolerance in percent. Unwind dust is bounded by
            this per iteration, so tighter slippage means less dust.
          default: '0.5'
          examples:
            - 0.3
            - 0.5
        allow_partial:
          type: boolean
          title: Allow Partial
          description: >-
            If the target cannot be reached in one transaction (e.g. a position
            opened very close to the liquidation threshold), return the
            maximum-progress plan (preview.fully_unwound=false) instead of a
            400. A second unloop call, now from a much lower leverage, finishes
            the job.
          default: false
          examples:
            - false
        gas_sponsorship:
          type: boolean
          title: Gas Sponsorship
          description: >-
            If true, returns EIP-712 typed data for gas-sponsored execution
            instead of an unsigned transaction.
          default: false
          examples:
            - false
      type: object
      required:
        - owner
        - chain
        - collateral_token
        - borrow_token
      title: CreditUnloopRequest
      description: |-
        Unwind a leveraged loop: repeatedly withdraw collateral, swap it back to
        the borrow token at a guaranteed minimum output, and repay — all in ONE
        atomic transaction from the Credit Account.
      default:
        owner: '0x0E407CdeBD8e078E6966ef6740540d25F5897082'
        chain: ethereum
        protocol: AAVE
        collateral_token: WETH
        borrow_token: USDC
        max_slippage_percent: 0.5
        allow_partial: false
        gas_sponsorship: false
    CreditUnloopResponse:
      properties:
        transaction:
          anyOf:
            - $ref: '#/components/schemas/UnsignedTransaction'
            - type: 'null'
          description: >-
            Unsigned transaction for direct execution by the owner. Present when
            gas_sponsorship=false.
        eip_712:
          anyOf:
            - $ref: '#/components/schemas/BatchedSafeOperationsResponse-Output'
            - type: 'null'
          description: >-
            EIP-712 typed data for gas-sponsored execution. Present when
            gas_sponsorship=true.
        preview:
          $ref: '#/components/schemas/CreditUnloopPreview'
          description: Projected end state, computed on guaranteed swap floors.
      type: object
      required:
        - preview
      title: CreditUnloopResponse
      description: The atomic unwind transaction plus its guaranteed-floor preview.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    Chain:
      type: string
      enum:
        - base
        - ethereum
        - arbitrum
        - hyperevm
        - tempo
        - bsc
      title: Chain
      description: The chain to use.
    CreditProtocol:
      type: string
      enum:
        - AAVE
        - EULER
        - MORPHO
      title: CreditProtocol
      description: >-
        Which lending protocol a credit action targets.


        ``AAVE`` is the default so existing callers (which never send a
        ``protocol``

        field) keep hitting the unchanged Aave code path. ``EULER`` opts in to
        the

        Euler V2 path, where the market is identified by EVK vault address(es).

        ``MORPHO`` identifies Morpho Blue lending markets (bytes32 market id)
        and is

        currently read-only: positions and market discovery only — transaction

        builders land with the looping work (COM-7106/7107/7108), so transact

        endpoints reject it with a 422.
    UnsignedTransaction:
      properties:
        chainId:
          type: string
          title: Chainid
          description: The chain id of the transaction
        data:
          type: string
          title: Data
          description: The data of the transaction
        from:
          type: string
          title: From
          description: The sender of the transaction
        gas:
          anyOf:
            - type: string
            - type: 'null'
          title: Gas
          description: The gas of the transaction
        to:
          type: string
          title: To
          description: The recipient of the transaction
        value:
          type: string
          title: Value
          description: The value of the transaction
        nonce:
          type: string
          title: Nonce
          description: The nonce of the address
        maxFeePerGas:
          type: string
          title: Maxfeepergas
          description: The max fee per gas of the transaction
        maxPriorityFeePerGas:
          type: string
          title: Maxpriorityfeepergas
          description: The max priority fee per gas of the transaction
      type: object
      required:
        - chainId
        - data
        - from
        - gas
        - to
        - value
        - nonce
        - maxFeePerGas
        - maxPriorityFeePerGas
      title: UnsignedTransaction
      example:
        chainId: '0x2105'
        data: >-
          0x1688f0b900000000000000000000000029fcb43b46531bca003ddc8fcb67ffe91900c762000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000675f4a3d
        from: '0x4A83b4413CF41C3244027e1590E35a0F48403F0c'
        gas: '0x7a120'
        maxFeePerGas: '0x59682f00'
        maxPriorityFeePerGas: '0x3b9aca00'
        nonce: '0x5'
        to: '0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67'
        value: '0x0'
    BatchedSafeOperationsResponse-Output:
      properties:
        domain:
          $ref: >-
            #/components/schemas/compass__api_backend__v2__models__safe__transact__response__batched_safe_operations__EIP712Domain
          description: EIP-712 domain separator
        types:
          $ref: >-
            #/components/schemas/compass__api_backend__v2__models__safe__transact__response__batched_safe_operations__EIP712Types
          description: EIP-712 type definitions
        primaryType:
          type: string
          const: SafeTx
          title: Primarytype
          description: Primary type for the structured data
        message:
          $ref: '#/components/schemas/SafeTxMessage'
          description: Safe transaction message data
      type: object
      required:
        - domain
        - types
        - primaryType
        - message
      title: BatchedSafeOperationsResponse
      description: Response containing EIP-712 typed data for Safe transaction signing.
      example:
        domain:
          chainId: 8453
          verifyingContract: '0x6B90E8B4E3E971E74C1A47a3a20976377E2dB4b1'
        message:
          baseGas: '0'
          data: >-
            0x8d80ff0a0000000000000000000000000000000000000000000000000000000000000020
          gasPrice: '0'
          gasToken: '0x0000000000000000000000000000000000000000'
          nonce: '7'
          operation: 1
          refundReceiver: '0x0000000000000000000000000000000000000000'
          safeTxGas: '0'
          to: '0x93C23AAE4793C14D6DF35D2A2A2234204e1559dA'
          value: '0'
        primaryType: SafeTx
        types:
          EIP712Domain:
            - name: chainId
              type: uint256
            - name: verifyingContract
              type: address
          SafeTx:
            - name: to
              type: address
            - name: value
              type: uint256
            - name: data
              type: bytes
            - name: operation
              type: uint8
            - name: safeTxGas
              type: uint256
            - name: baseGas
              type: uint256
            - name: gasPrice
              type: uint256
            - name: gasToken
              type: address
            - name: refundReceiver
              type: address
            - name: nonce
              type: uint256
    CreditUnloopPreview:
      properties:
        iterations:
          type: integer
          title: Iterations
          description: >-
            Number of swap-bearing unwind iterations bundled (the final
            collateral sweep leg does not count).
        total_collateral_withdrawn:
          type: string
          title: Total Collateral Withdrawn
          description: Guaranteed minimum total collateral withdrawn (token units).
        total_debt_repaid:
          type: string
          title: Total Debt Repaid
          description: >-
            Guaranteed minimum total debt repaid (borrow-token units); actual
            can only be higher (swap fills above the floor repay more).
        ending_collateral:
          type: string
          title: Ending Collateral
          description: >-
            Pair collateral left supplied after the unwind (token units). On a
            full close this is 0, except when non-pair Aave debt still needs
            this collateral as backing — then the final sweep is capped and this
            reports the residual left supplied.
        ending_debt:
          type: string
          title: Ending Debt
          description: Projected remaining debt (borrow-token units); 0 on a full close.
        ending_multiplier:
          type: string
          title: Ending Multiplier
          description: >-
            Projected leverage after the unwind; 1 when the debt is cleared.
            Never promises more deleverage than is guaranteed.
        projected_ltv:
          type: string
          title: Projected Ltv
          description: >-
            Projected end loan-to-value in percent, at the sizing oracle prices;
            0 when the debt is cleared.
        projected_health_factor:
          type: string
          title: Projected Health Factor
          description: >-
            Projected health factor (Aave account-level / Morpho market-level).
            Never overstated at the 1.0 boundary.
        estimated_max_dust:
          type: string
          title: Estimated Max Dust
          description: >-
            Upper bound of borrow-token surplus the unwind can leave in the
            Credit Account — the sum of each swap's quote minus its guaranteed
            floor plus the full-close overshoot. It accumulates in the Credit
            Account, is recoverable, and is never lost.
        fully_unwound:
          type: boolean
          title: Fully Unwound
          description: >-
            True when the requested target was fully reached in this
            transaction. False on a partial-progress plan (allow_partial=true) —
            call unloop again to finish.
        legs:
          items:
            $ref: '#/components/schemas/UnloopLegPreview'
          type: array
          title: Legs
          description: Per-iteration breakdown.
          default: []
      additionalProperties: false
      type: object
      required:
        - iterations
        - total_collateral_withdrawn
        - total_debt_repaid
        - ending_collateral
        - ending_debt
        - ending_multiplier
        - projected_ltv
        - projected_health_factor
        - estimated_max_dust
        - fully_unwound
      title: CreditUnloopPreview
      description: Projected end state of the unwind, computed on GUARANTEED swap floors.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    compass__api_backend__v2__models__safe__transact__response__batched_safe_operations__EIP712Domain:
      properties:
        chainId:
          type: integer
          title: Chainid
          description: Chain ID
        verifyingContract:
          type: string
          title: Verifyingcontract
          description: Address of the Product Account
      type: object
      required:
        - chainId
        - verifyingContract
      title: EIP712Domain
      description: The EIP-712 domain separator.
    compass__api_backend__v2__models__safe__transact__response__batched_safe_operations__EIP712Types:
      properties:
        EIP712Domain:
          items:
            $ref: '#/components/schemas/EIP712DomainField'
          type: array
          title: Eip712Domain
          description: EIP712Domain type definition
        SafeTx:
          items:
            $ref: '#/components/schemas/SafeTxField'
          type: array
          title: Safetx
          description: SafeTx type definition
      type: object
      required:
        - EIP712Domain
        - SafeTx
      title: EIP712Types
      description: The type definitions for EIP-712 structured data.
    SafeTxMessage:
      properties:
        to:
          type: string
          title: To
          description: Destination address
        value:
          type: string
          title: Value
          description: Value in wei as a string
        data:
          type: string
          title: Data
          description: Transaction data as hex string
        operation:
          $ref: '#/components/schemas/OperationType'
          description: Operation type (0=Call, 1=DelegateCall)
        safeTxGas:
          type: string
          title: Safetxgas
          description: Gas for the transaction
        baseGas:
          type: string
          title: Basegas
          description: Base gas costs
        gasPrice:
          type: string
          title: Gasprice
          description: Gas price
        gasToken:
          type: string
          title: Gastoken
          description: Token address for gas payment
        refundReceiver:
          type: string
          title: Refundreceiver
          description: Address to receive gas refund
        nonce:
          type: string
          title: Nonce
          description: Transaction nonce
      type: object
      required:
        - to
        - value
        - data
        - operation
        - safeTxGas
        - baseGas
        - gasPrice
        - gasToken
        - refundReceiver
        - nonce
      title: SafeTxMessage
      description: The message data for the transaction.
    UnloopLegPreview:
      properties:
        withdraw_amount:
          anyOf:
            - type: string
            - type: 'null'
          title: Withdraw Amount
          description: Collateral withdrawn this iteration (token units).
        min_swap_out:
          anyOf:
            - type: string
            - type: 'null'
          title: Min Swap Out
          description: >-
            Guaranteed swap output (borrow-token units) — enforced on-chain by
            the swap's minimum-return. Null on the final collateral sweep leg,
            which does not swap.
        repay_amount:
          anyOf:
            - type: string
            - type: 'null'
          title: Repay Amount
          description: >-
            Debt repaid this iteration (borrow-token units); null on the final
            collateral sweep leg.
        full_repay:
          type: boolean
          title: Full Repay
          description: >-
            True on the closing leg that clears the remaining debt exactly (Aave
            clamps to live debt; Morpho repays the remaining shares).
          default: false
      additionalProperties: false
      type: object
      required:
        - withdraw_amount
      title: UnloopLegPreview
      description: 'One planned unwind iteration: withdraw [+ swap + repay].'
    EIP712DomainField:
      properties:
        name:
          type: string
          title: Name
        type:
          type: string
          title: Type
      type: object
      required:
        - name
        - type
      title: EIP712DomainField
      description: A field in the EIP712Domain type definition.
    SafeTxField:
      properties:
        name:
          type: string
          title: Name
        type:
          type: string
          title: Type
      type: object
      required:
        - name
        - type
      title: SafeTxField
      description: A field in the SafeTx type definition.
    OperationType:
      type: integer
      enum:
        - 0
        - 1
      title: OperationType
      description: Safe operation types.
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        Your Compass API Key. Get your key
        [here](https://www.compasslabs.ai/dashboard).

````