> ## 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.

# Open a leveraged loop

> Open a leveraged loop into an Aave or Morpho market in ONE atomic transaction.

Repeatedly supplies collateral, borrows at the requested loan-to-value, and
swaps the borrow back to collateral. Each iteration's supply uses the swap's
GUARANTEED minimum output (enforced on-chain), so a fill anywhere within the
slippage tolerance can never break a later step; any positive surplus stays
in the Credit Account (the preview reports the bound as estimated_max_dust).
Very large loops relative to pool depth can still exceed the slippage
tolerance through their own cumulative price impact — size accordingly or
raise max_slippage_percent.

The Credit Account must already hold initial_collateral_amount of
collateral_token. For protocol=MORPHO pass a market_id from
/v2/credit/morpho_markets.



## OpenAPI

````yaml /v2/combined_spec.json post /v2/credit/loop
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/loop:
    post:
      tags:
        - Credit
      summary: Open a leveraged loop
      description: >-
        Open a leveraged loop into an Aave or Morpho market in ONE atomic
        transaction.


        Repeatedly supplies collateral, borrows at the requested loan-to-value,
        and

        swaps the borrow back to collateral. Each iteration's supply uses the
        swap's

        GUARANTEED minimum output (enforced on-chain), so a fill anywhere within
        the

        slippage tolerance can never break a later step; any positive surplus
        stays

        in the Credit Account (the preview reports the bound as
        estimated_max_dust).

        Very large loops relative to pool depth can still exceed the slippage

        tolerance through their own cumulative price impact — size accordingly
        or

        raise max_slippage_percent.


        The Credit Account must already hold initial_collateral_amount of

        collateral_token. For protocol=MORPHO pass a market_id from

        /v2/credit/morpho_markets.
      operationId: v2_credit_loop
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreditLoopRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreditLoopResponse'
        '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_loop(owner="0x5e5b00ed886A6879C2B934612D2312975427fcAf", chain=models.Chain.ETHEREUM, collateral_token="WETH", borrow_token="USDC", initial_collateral_amount=1, multiplier=2, loan_to_value=70, protocol=models.CreditProtocol.AAVE, max_slippage_percent=0.5, 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.creditLoop({
                owner: "0x5e5b00ed886A6879C2B934612D2312975427fcAf",
                chain: "ethereum",
                protocol: "AAVE",
                collateralToken: "WETH",
                borrowToken: "USDC",
                initialCollateralAmount: 1,
                multiplier: 2,
                loanToValue: 70,
                maxSlippagePercent: 0.5,
                gasSponsorship: false,
              });

              console.log(result);
            }

            run();
components:
  schemas:
    CreditLoopRequest:
      properties:
        owner:
          type: string
          title: Owner
          description: The address that owns the Credit Account.
          default: '0x5e5b00ed886A6879C2B934612D2312975427fcAf'
          examples:
            - '0x5e5b00ed886A6879C2B934612D2312975427fcAf'
        chain:
          $ref: '#/components/schemas/Chain'
          description: Blockchain network.
          default: ethereum
          examples:
            - ethereum
        protocol:
          $ref: '#/components/schemas/CreditProtocol'
          description: >-
            Lending protocol to loop into: AAVE or MORPHO. EULER looping 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 each iteration. Must already be in the
            Credit Account for the initial amount. For MORPHO it must be the
            market's collateral token.
          examples:
            - wstETH
            - WETH
          default: WETH
        borrow_token:
          type: string
          title: Token
          description: >-
            Token borrowed each iteration and swapped back to the collateral
            token. For MORPHO it must be the market's loan token.
          examples:
            - WETH
            - USDC
          default: USDC
        initial_collateral_amount:
          anyOf:
            - type: number
              exclusiveMinimum: 0
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Initial Collateral Amount
          description: >-
            Collateral (in token units) already held in the Credit Account to
            seed the loop.
          examples:
            - 1.5
            - 1000
          default: 1
        multiplier:
          anyOf:
            - type: number
              exclusiveMinimum: 1
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Multiplier
          description: >-
            Target leverage: total collateral exposure = multiplier ×
            initial_collateral_amount. Must be achievable at the requested
            loan_to_value (max ≈ 0.9 / (1 − LTV)).
          examples:
            - 2
            - 3
          default: 2
        loan_to_value:
          anyOf:
            - type: number
              maximum: 100
              exclusiveMinimum: 0
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Loan To Value
          description: >-
            Per-iteration borrow LTV in percent. Must not exceed the protocol's
            maximum for the market (Aave reserve/e-mode LTV; Morpho LLTV with a
            safety margin); borrows are sized slightly inside the requested
            value so no leg sits on the protocol's revert boundary.
          examples:
            - 70
            - 86
          default: 70
        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. Loop dust is bounded by this
            per iteration, so tighter slippage means less dust.
          default: '0.5'
          examples:
            - 0.3
            - 0.5
        emode_category:
          anyOf:
            - type: integer
              minimum: 0
            - type: 'null'
          title: Emode Category
          description: >-
            Aave only: e-mode category to enable before looping (higher LTV for
            correlated pairs, e.g. ETH-correlated).
        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
        - initial_collateral_amount
        - multiplier
        - loan_to_value
      title: CreditLoopRequest
      description: >-
        Open a leveraged loop: repeatedly supply collateral, borrow, and swap
        the

        borrow back to collateral — all in ONE atomic transaction from the
        Credit

        Account.
      default:
        owner: '0x5e5b00ed886A6879C2B934612D2312975427fcAf'
        chain: ethereum
        protocol: AAVE
        collateral_token: WETH
        borrow_token: USDC
        initial_collateral_amount: 1
        multiplier: 2
        loan_to_value: 70
        max_slippage_percent: 0.5
        gas_sponsorship: false
    CreditLoopResponse:
      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/CreditLoopPreview'
          description: Projected end state, computed on guaranteed swap floors.
      type: object
      required:
        - preview
      title: CreditLoopResponse
      description: The atomic loop 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
    CreditLoopPreview:
      properties:
        iterations:
          type: integer
          title: Iterations
          description: Number of loop iterations bundled.
        total_collateral_supplied:
          type: string
          title: Total Collateral Supplied
          description: >-
            Guaranteed minimum total collateral supplied (token units); actual
            can only be higher (swap fills above the floor become dust).
        total_borrowed:
          type: string
          title: Total Borrowed
          description: Total loan tokens borrowed across iterations.
        achieved_multiplier:
          type: string
          title: Achieved Multiplier
          description: >-
            Guaranteed leverage floor: total_collateral_supplied /
            initial_collateral_amount.
        projected_ltv:
          type: string
          title: Projected Ltv
          description: Projected end loan-to-value in percent, at the sizing oracle prices.
        projected_health_factor:
          type: string
          title: Projected Health Factor
          description: >-
            Projected health factor (liquidation threshold / projected LTV).
            Below 1 would be liquidatable — the request is rejected long before
            that.
        estimated_max_dust:
          type: string
          title: Estimated Max Dust
          description: >-
            Upper bound of collateral-token surplus the swaps can leave in the
            Credit Account (sum of quote − guaranteed floor per swap). It is
            bounded by max_slippage_percent per iteration, stays in the account,
            and is never lost.
        legs:
          items:
            $ref: '#/components/schemas/LoopLegPreview'
          type: array
          title: Legs
          description: Per-iteration breakdown.
          default: []
      additionalProperties: false
      type: object
      required:
        - iterations
        - total_collateral_supplied
        - total_borrowed
        - achieved_multiplier
        - projected_ltv
        - projected_health_factor
        - estimated_max_dust
      title: CreditLoopPreview
      description: Projected end state of the loop, 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.
    LoopLegPreview:
      properties:
        supply_amount:
          anyOf:
            - type: string
            - type: 'null'
          title: Supply Amount
          description: Collateral supplied this iteration (token units).
        borrow_amount:
          anyOf:
            - type: string
            - type: 'null'
          title: Borrow Amount
          description: >-
            Loan borrowed this iteration; null on the final supply-only
            iteration.
        min_swap_out:
          anyOf:
            - type: string
            - type: 'null'
          title: Min Swap Out
          description: >-
            Guaranteed swap output (collateral units) — the next iteration's
            supply. Enforced on-chain by the swap's minimum-return.
      additionalProperties: false
      type: object
      required:
        - supply_amount
      title: LoopLegPreview
      description: One planned loop iteration.
    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).

````