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

# Swap collateral

> Enables safe rebalancing of collateral by withdrawing a selected asset, executing CPIs (e.g. swaps or liquidity provision), and depositing a new asset in its place.



## OpenAPI

````yaml post /markets/creditbook/swap_collateral
openapi: 3.1.0
info:
  title: Loopscale API
  version: 0.1.0
servers:
  - url: https://tars.loopscale.com/v1
    description: Loopscale Production Server
security: []
paths:
  /markets/creditbook/swap_collateral:
    post:
      tags:
        - creditbook
      summary: Swap collateral
      description: >-
        Enables safe rebalancing of collateral by withdrawing a selected asset,
        executing CPIs (e.g. swaps or liquidity provision), and depositing a new
        asset in its place.
      operationId: query_swap_collateral
      parameters:
        - name: Idempotent-Key
          in: header
          description: >-
            Optional idempotency key; a retried write with the same key replays
            the original response
          required: false
          schema:
            type:
              - string
              - 'null'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TxnSwapCollateralParams'
        required: true
      responses:
        '200':
          description: Single versioned transaction message and signatures
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/LoanTxnResponse'
        '400':
          description: Invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: Idempotency-Key reused with a different request body
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
components:
  schemas:
    TxnSwapCollateralParams:
      type: object
      required:
        - loan
        - withdrawCollateral
        - depositCollateral
      properties:
        cpiIxs:
          type: array
          items:
            $ref: '#/components/schemas/ParsedInstruction'
          description: Caller-supplied CPI instructions spliced into the built transaction.
        cpiLuts:
          type: array
          items:
            type: string
        cpiSigners:
          type: array
          items:
            type: string
        depositCollateral:
          type: array
          items:
            $ref: '#/components/schemas/DepositCollateralInput'
        loan:
          type: string
        withdrawCollateral:
          type: array
          items:
            $ref: '#/components/schemas/WithdrawCollateralParams'
    LoanTxnResponse:
      type: object
      required:
        - transactions
        - expectedLoanInfo
      properties:
        expectedLoanInfo:
          $ref: '#/components/schemas/LoanInfo'
          description: Projected loan state after the transactions land.
        transactions:
          type: array
          items:
            $ref: '#/components/schemas/VersionedTransactionReturn'
          description: Built, ready-to-sign versioned transactions.
    ErrorResponse:
      type: object
      description: |-
        Canonical error envelope for every endpoint. The `x-request-id` response
        header carries the correlation id for the failing request.
      required:
        - error
      properties:
        error:
          $ref: '#/components/schemas/ErrorDetails'
          description: error detail
    ParsedInstruction:
      type: object
      description: >-
        A parsed Solana instruction (program id, ordered account metas, and
        base58

        instruction data) spliced verbatim into a built transaction as a CPI.
      required:
        - programId
        - accounts
        - data
      properties:
        accounts:
          type: array
          items:
            $ref: '#/components/schemas/ParsedAccountMeta'
          description: ordered account metas
        data:
          type: string
          description: base58-encoded instruction data
        programId:
          type: string
          description: program id (base58)
    DepositCollateralInput:
      type: object
      required:
        - collateralAmount
        - collateralAssetData
      properties:
        collateralAmount:
          type: integer
          format: int64
          minimum: 0
        collateralAssetData:
          $ref: '#/components/schemas/AssetDataInfo'
        loanCreationParams:
          oneOf:
            - type: 'null'
            - $ref: '#/components/schemas/LoanCreationParams'
        weightMatrixUpdate:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
    WithdrawCollateralParams:
      type: object
      required:
        - collateralMint
        - amount
      properties:
        amount:
          type: integer
          format: int64
          minimum: 0
        closeIfEligible:
          type: boolean
        collateralMint:
          type: string
    LoanInfo:
      type: object
      required:
        - loan
        - loanType
        - ledgers
        - collateral
        - collateralYieldPct
        - principalYieldPct
      properties:
        collateral:
          type: array
          items:
            $ref: '#/components/schemas/LoanCollateral'
        collateralYieldPct:
          type: number
          format: double
        events:
          type: array
          items:
            $ref: '#/components/schemas/GenericParsedLoanEvent'
        ledgers:
          type: array
          items:
            $ref: '#/components/schemas/Ledger'
        loan:
          $ref: '#/components/schemas/Loan'
        loanType:
          type: integer
          format: int32
          minimum: 0
        matrixUpdates:
          type: array
          items:
            $ref: '#/components/schemas/LoanMatrixEvent'
        pastLedgers:
          type: array
          items:
            $ref: '#/components/schemas/Ledger'
        principalYieldPct:
          type: number
          format: double
    VersionedTransactionReturn:
      type: object
      description: versioned txn return
      required:
        - message
        - signatures
      properties:
        message:
          type: string
          description: serialized message
        signatures:
          type: array
          items:
            $ref: '#/components/schemas/VersionedTransactionSignature'
          description: serialized signatures
    ErrorDetails:
      type: object
      description: Inner detail of the [`ErrorResponse`] envelope.
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
          description: HTTP status code, mirrored in the response status line
          example: 400
          minimum: 0
        message:
          type: string
          description: human-readable, client-safe message (sensitive data redacted)
          example: Request could not be processed.
    ParsedAccountMeta:
      type: object
      description: One account reference of a parsed Solana instruction.
      required:
        - pubkey
        - isSigner
        - isWritable
      properties:
        isSigner:
          type: boolean
          description: whether the account must sign
        isWritable:
          type: boolean
          description: whether the account is written
        pubkey:
          type: string
          description: account pubkey (base58)
    AssetDataInfo:
      oneOf:
        - type: object
          required:
            - Spl
          properties:
            Spl:
              $ref: '#/components/schemas/SplData'
        - type: object
          required:
            - StakedSol
          properties:
            StakedSol:
              $ref: '#/components/schemas/StakedSolData'
        - type: object
          required:
            - Orca
          properties:
            Orca:
              $ref: '#/components/schemas/OrcaPositionData'
        - type: object
          required:
            - Meteora
          properties:
            Meteora:
              $ref: '#/components/schemas/MeteoraDlmmPositionData'
        - type: object
          required:
            - Raydium
          properties:
            Raydium:
              $ref: '#/components/schemas/RaydiumPositionData'
      description: |-
        Collateral asset identification, tagged by collateral kind (SPL token,
        staked SOL, or a CLMM LP position on Orca / Meteora / Raydium).
    LoanCreationParams:
      oneOf:
        - type: string
          enum:
            - Default
        - type: object
          required:
            - OrcaPositionCreate
          properties:
            OrcaPositionCreate:
              $ref: '#/components/schemas/OrcaPositionCreateParams'
      description: >-
        Optional collateral-specific loan-creation params (e.g. opening an Orca
        CLMM

        position as collateral); `Default` for a plain loan.
    LoanCollateral:
      type: object
      required:
        - loan
        - index
        - assetType
        - assetIdentifier
        - assetMint
        - amount
      properties:
        amount:
          type: integer
          format: int64
          minimum: 0
        assetIdentifier:
          type: string
        assetMint:
          type: string
        assetType:
          type: integer
          format: int32
          minimum: 0
        id:
          type: integer
          format: int32
          minimum: 0
        index:
          type: integer
          format: int32
          minimum: 0
        lastInteractedTime:
          type: integer
          format: int64
          minimum: 0
        lastInteractedTxn:
          type: string
        loan:
          type: string
        writeVersion:
          type: integer
          format: int64
          minimum: 0
    GenericParsedLoanEvent:
      type: object
      description: >-
        A parsed loan lifecycle event with action-specific metadata in
        `actionMetadata`.
      required:
        - id
        - loan
        - assetIdentifier
        - amount
        - action
        - actionMetadata
        - eventTime
        - eventTxn
      properties:
        action:
          $ref: '#/components/schemas/LoanEventType'
        actionMetadata:
          $ref: '#/components/schemas/ApiLoanEventActionMetadata'
        amount:
          type: integer
          format: int64
          minimum: 0
        assetIdentifier:
          type: string
        assetMint:
          type:
            - string
            - 'null'
        eventTime:
          type: integer
          format: int64
          minimum: 0
        eventTxn:
          type: string
        id:
          type: integer
          format: int32
          minimum: 0
        loan:
          type: string
        newLender:
          type:
            - string
            - 'null'
        originalLender:
          type:
            - string
            - 'null'
        usdPrice:
          type:
            - number
            - 'null'
          format: double
    Ledger:
      type: object
      required:
        - ledgerIndex
        - loan
        - status
        - strategy
        - principalMint
        - marketInformation
        - principalDue
        - principalRepaid
        - interestOutstanding
        - lastInterestUpdatedTime
        - interestPerSecond
        - duration
        - durationType
        - startTime
        - endTime
        - apy
        - weights
        - ltvRatios
        - lqtRatios
        - lastInteractedTime
        - lastInteractedTxn
      properties:
        apy:
          type: integer
          format: int64
          minimum: 0
        duration:
          type: integer
          format: int32
          minimum: 0
        durationType:
          type: integer
          format: int32
          minimum: 0
        endTime:
          type: integer
          format: int64
          minimum: 0
        id:
          type: integer
          format: int32
          minimum: 0
        interestOutstanding:
          type: integer
          format: int64
          minimum: 0
        interestPerSecond:
          type: number
          format: double
        isLoop:
          type: integer
          format: int32
        lastInteractedTime:
          type: integer
          format: int64
          minimum: 0
        lastInteractedTxn:
          type: string
        lastInterestUpdatedTime:
          type: integer
          format: int64
          minimum: 0
        ledgerIndex:
          type: integer
          format: int32
          minimum: 0
        loan:
          type: string
        lqtRatios:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: >-
            Per-collateral liquidation thresholds (cbps), same index order as
            `weights`.
        ltvRatios:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: >-
            Per-collateral loan-to-value ratios (cbps), same index order as
            `weights`.
        marketInformation:
          type: string
        principalDue:
          type: integer
          format: int64
          minimum: 0
        principalMint:
          type: string
        principalRepaid:
          type: integer
          format: int64
          minimum: 0
        startTime:
          type: integer
          format: int64
          minimum: 0
        status:
          type: integer
          format: int32
          minimum: 0
        strategy:
          type: string
        weights:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: >-
            Weight matrix: per-collateral weight (cbps), indexed by the market's

            collateral map. Drives how each collateral backs this ledger's
            principal.
        writeVersion:
          type: integer
          format: int64
          minimum: 0
    Loan:
      type: object
      required:
        - address
        - bump
        - loanStatus
        - nonce
        - borrower
        - startTime
        - closed
        - lastInteractedTime
        - lastInteractedTxn
        - writeVersion
      properties:
        address:
          type: string
        borrower:
          type: string
        bump:
          type: integer
          format: int32
          minimum: 0
        closed:
          type: boolean
        id:
          type: integer
          format: int32
          minimum: 0
        lastInteractedTime:
          type: integer
          format: int64
          minimum: 0
        lastInteractedTxn:
          type: string
        loanStatus:
          type: integer
          format: int32
          minimum: 0
        nonce:
          type: integer
          format: int64
          minimum: 0
        startTime:
          type: integer
          format: int64
          minimum: 0
        writeVersion:
          type: integer
          format: int64
          minimum: 0
    LoanMatrixEvent:
      type: object
      description: >-
        A recorded weight-matrix update on a loan: the new per-collateral weight
        / LTV

        / LQT matrices at a point in time (one row per `update_weight_matrix`).
      required:
        - loan
        - weights
        - lqtRatios
        - ltvRatios
        - timestamp
        - txnSignature
        - ledgerIndex
        - writeVersion
      properties:
        id:
          type: integer
          format: int32
          minimum: 0
        ledgerIndex:
          type: integer
          format: int32
          minimum: 0
        loan:
          type: string
        lqtRatios:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: Per-collateral liquidation thresholds (cbps) after this update.
        ltvRatios:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: Per-collateral loan-to-value ratios (cbps) after this update.
        timestamp:
          type: integer
          format: int64
          minimum: 0
        txnSignature:
          type: string
        weights:
          type: array
          items:
            type: integer
            format: int32
            minimum: 0
          description: Weight matrix (per-collateral weight, cbps) after this update.
        writeVersion:
          type: integer
          format: int64
          minimum: 0
    VersionedTransactionSignature:
      type: object
      description: versioned txn return
      required:
        - publicKey
        - signature
      properties:
        publicKey:
          type: string
          description: serialized message
        signature:
          type: string
          description: serialized signatures
    SplData:
      type: object
      required:
        - mint
      properties:
        mint:
          type: string
    StakedSolData:
      type: object
      required:
        - stakeAccount
        - stakePool
      properties:
        stakeAccount:
          type: string
        stakePool:
          type: string
    OrcaPositionData:
      type: object
      required:
        - positionMint
        - whirlpool
      properties:
        positionMint:
          type: string
        tokenProgram:
          type:
            - string
            - 'null'
        whirlpool:
          type: string
    MeteoraDlmmPositionData:
      type: object
      required:
        - positionAddress
        - lbPair
      properties:
        lbPair:
          type: string
        positionAddress:
          type: string
        tokenProgram:
          type:
            - string
            - 'null'
    RaydiumPositionData:
      type: object
      required:
        - mint
        - pool
      properties:
        mint:
          type: string
        pool:
          type: string
        tokenProgram:
          type:
            - string
            - 'null'
    OrcaPositionCreateParams:
      type: object
      required:
        - upperTick
        - lowerTick
        - tickSpacing
        - whirlpool
        - tokenMintA
        - tokenMintB
      properties:
        lowerTick:
          type: integer
          format: int32
        tickSpacing:
          type: integer
          format: int32
        tokenMintA:
          type: string
        tokenMintB:
          type: string
        upperTick:
          type: integer
          format: int32
        whirlpool:
          type: string
    LoanEventType:
      type: string
      enum:
        - addCollateral
        - removeCollateral
        - borrowPrincipal
        - repayPrincipal
        - refinanceLedger
        - sellLedger
        - liquidate
    ApiLoanEventActionMetadata:
      oneOf:
        - type: object
          required:
            - type
          properties:
            type:
              type: string
              enum:
                - addCollateral
        - type: object
          required:
            - type
          properties:
            type:
              type: string
              enum:
                - removeCollateral
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedBorrowPrincipalMetadata'
            type:
              type: string
              enum:
                - borrowPrincipal
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedRepayPrincipalMetadata'
            type:
              type: string
              enum:
                - repayPrincipal
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedRefinanceLedgerMetadata'
            type:
              type: string
              enum:
                - refinanceLedger
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedSellLedgerMetadata'
            type:
              type: string
              enum:
                - sellLedger
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedLiquidateLedgerMetadata'
            type:
              type: string
              enum:
                - liquidate
        - type: object
          required:
            - params
            - type
          properties:
            params:
              $ref: '#/components/schemas/ParsedMigrateLedgerMetadata'
            type:
              type: string
              enum:
                - migrate
      description: |-
        API-specific representation of loan event metadata (adjacently-tagged:
        `{ "type": <action>, "params": <metadata> }`).
    ParsedBorrowPrincipalMetadata:
      type: object
      required:
        - preBorrowPrincipalLedgerState
        - postBorrowPrincipalLedgerState
      properties:
        postBorrowPrincipalLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
        preBorrowPrincipalLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
    ParsedRepayPrincipalMetadata:
      type: object
      required:
        - preRepaymentPrincipalLedgerState
        - postRepaymentPrincipalLedgerState
      properties:
        postRepaymentPrincipalLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
        preRepaymentPrincipalLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
    ParsedRefinanceLedgerMetadata:
      type: object
      required:
        - preRefinanceLedgerState
        - postRefinanceLedgerState
      properties:
        postRefinanceLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
        preRefinanceLedgerState:
          $ref: '#/components/schemas/ParsedEventLedger'
    ParsedSellLedgerMetadata:
      type: object
      required:
        - buyer
        - seller
      properties:
        buyer:
          type: string
        seller:
          type: string
    ParsedLiquidateLedgerMetadata:
      type: object
      required:
        - ledgerIndex
        - isTimeBasedLiquidation
        - collateralTransfers
        - liquidationFee
      properties:
        collateralTransfers:
          type: array
          items:
            $ref: '#/components/schemas/ParsedLiquidatedCollateralMetadata'
        isTimeBasedLiquidation:
          type: boolean
        ledgerIndex:
          type: integer
          minimum: 0
        liquidationFee:
          type: number
          format: double
    ParsedMigrateLedgerMetadata:
      type: object
      required:
        - lockboxAddr
      properties:
        lockboxAddr:
          type: string
    ParsedEventLedger:
      type: object
      description: >-
        Snapshot of a ledger's state captured in an event's before/after
        metadata.
      required:
        - status
        - strategy
        - principalMint
        - marketInformation
        - principalDue
        - principalRepaid
        - duration
        - interestPerSecond
        - apy
        - endTime
        - startTime
      properties:
        apy:
          type: integer
          format: int64
          minimum: 0
        duration:
          $ref: '#/components/schemas/StrategyDuration'
        endTime:
          type: integer
          format: int64
          minimum: 0
        interestOutstanding:
          type: integer
          format: int64
          minimum: 0
        interestPerSecond:
          type: number
          format: double
        lastInterestUpdatedTime:
          type: integer
          format: int64
          minimum: 0
        ledgerIndex:
          type: integer
          minimum: 0
        marketInformation:
          type: string
        principalDue:
          type: integer
          format: int64
          minimum: 0
        principalMint:
          type: string
        principalRepaid:
          type: integer
          format: int64
          minimum: 0
        startTime:
          type: integer
          format: int64
          minimum: 0
        status:
          type: integer
          format: int32
          minimum: 0
        strategy:
          type: string
    ParsedLiquidatedCollateralMetadata:
      type: object
      required:
        - assetMint
        - amount
        - toLiquidator
        - price
      properties:
        amount:
          type: integer
          format: int64
          minimum: 0
        assetMint:
          type: string
        price:
          type: number
          format: double
        toLiquidator:
          type: boolean
    StrategyDuration:
      type: object
      required:
        - duration
        - durationType
      properties:
        duration:
          type: integer
          format: int32
          minimum: 0
        durationType:
          type: integer
          format: int32
          minimum: 0

````