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

# Swap tokens

> Swap one token for another inside a Credit Account.

Exchanges tokens the Credit Account already holds in a single atomic
transaction, so idle or borrowed balances can be converted without moving
funds out first. Returns an unsigned transaction to sign, the expected
output amount, and which route priced the swap.



## OpenAPI

````yaml /v2/combined_spec.json post /v2/credit/swap
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/swap:
    post:
      tags:
        - Credit
      summary: Swap tokens
      description: >-
        Swap one token for another inside a Credit Account.


        Exchanges tokens the Credit Account already holds in a single atomic

        transaction, so idle or borrowed balances can be converted without
        moving

        funds out first. Returns an unsigned transaction to sign, the expected

        output amount, and which route priced the swap.
      operationId: v2_credit_swap
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreditSwapRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreditSwapResponse'
        '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_swap(token_in="USDC", token_out="USDT", amount_in="0.01", owner="0x06A9aF046187895AcFc7258450B15397CAc67400", chain=models.CreditSwapRequestChain.BASE, slippage="0.5", gas_sponsorship=False, preview=False, pricing=models.CreditSwapRequestPricing.AUTO)

                # 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.creditSwap({
                tokenIn: "USDC",
                tokenOut: "USDT",
                amountIn: "0.01",
                slippage: "0.5",
                owner: "0x06A9aF046187895AcFc7258450B15397CAc67400",
                chain: "base",
                gasSponsorship: false,
                pricing: "auto",
              });

              console.log(result);
            }

            run();
components:
  schemas:
    CreditSwapRequest:
      properties:
        action_type:
          type: string
          const: V2_SWAP
          title: Action Type
          description: Action type identifier for swap operations.
          default: V2_SWAP
        token_in:
          type: string
          title: Token
          description: >-
            Token to sell (input). Provide a token symbol from a limited set
            (e.g., 'USDC') or any token address.
          examples:
            - USDC
            - '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'
          default: USDC
        token_out:
          type: string
          title: Token
          description: >-
            Token to buy (output). Provide a token symbol from a limited set
            (e.g., 'USDT') or any token address.
          examples:
            - USDT
            - '0xdAC17F958D2ee523a2206206994597C13D831ec7'
          default: USDT
        amount_in:
          anyOf:
            - type: number
              exclusiveMinimum: 0
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Amount In
          description: Human-readable amount of `token_in` to swap (token units, not wei).
          examples:
            - 1.5
          default: '0.01'
        slippage:
          anyOf:
            - type: number
              maximum: 10
              minimum: 0
            - type: string
              pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Slippage
          description: >-
            Maximum slippage tolerance as a percentage (e.g., 0.5 = 0.5%).
            Bounds the market route only; a firm quote fills exactly and ignores
            it.
          default: '0.5'
          examples:
            - 0.5
        owner:
          type: string
          title: Owner
          description: >-
            The owner's wallet address. Their Credit Account must already exist
            (create it with `/v2/credit/create_account`) and hold `token_in`
            (deposit with `/v2/credit/transfer`).
          default: '0x06A9aF046187895AcFc7258450B15397CAc67400'
          examples:
            - '0x06A9aF046187895AcFc7258450B15397CAc67400'
        chain:
          type: string
          enum:
            - arbitrum
            - base
            - bsc
            - ethereum
            - hyperevm
            - tempo
          title: Chain
          description: Target blockchain network where the swap will execute.
          default: base
          examples:
            - base
        gas_sponsorship:
          type: boolean
          title: Gas Sponsorship
          description: >-
            Optionally request gas sponsorship. If `true`, EIP-712 typed data
            will be returned that must be signed by the `owner` and submitted to
            the 'Prepare gas-sponsored transaction' endpoint
            (`/gas_sponsorship/prepare`). Gas-sponsored builds always execute at
            market rate.
          default: false
          examples:
            - false
        preview:
          type: boolean
          title: Preview
          description: >-
            If true, build a display ESTIMATE: no firm RFQ quote is ever
            requested (quote_expires_at stays null). NOTE that this guarantees
            only that no firm quote was spent — it does not guarantee an absent
            payload: under 'auto' when the firm provider does not cover or
            cannot currently price the pair, and always under pricing=market,
            the call falls through to the aggregator and returns a signable
            market build (an unsigned transaction, or EIP-712 typed data when
            gas_sponsorship=true), without requiring the account to hold
            token_in yet. How the estimate is priced follows `pricing`: on a
            firm-covered pair whose size the firm provider's live price levels
            can serve, 'auto' and 'firm' price it from those levels (indicative,
            transaction stays null — re-call with preview=false for the signable
            build); otherwise it comes from the market build above
            (pricing='firm' instead refuses with a typed error). Set it on every
            call made while a user is exploring parameters, and leave it false
            only for the build they actually intend to sign — firm quotes are
            single-use maker commitments, and requesting them for displays that
            are never executed degrades the pricing this API is offered.
          default: false
        pricing:
          type: string
          enum:
            - auto
            - firm
            - market
          title: Pricing
          description: >-
            Swap routing policy. 'auto': a firm zero-slippage quote when a firm
            venue covers the pair, transparent fallback to the market aggregator
            otherwise. 'firm': never price on the market route; an uncovered
            pair fails with a typed error instead of silently substituting
            market pricing — previews included: a preview the firm provider's
            live price levels cannot price returns the same typed error rather
            than market numbers. 'market': never route through the firm venue;
            the swap is priced by the aggregator and bounded by `slippage`
            (which firm fills ignore). 'firm' is incompatible with
            gas_sponsorship (sponsored swaps force market routing).
          default: auto
          examples:
            - auto
      type: object
      required:
        - token_in
        - token_out
        - amount_in
        - owner
        - chain
      title: CreditSwapRequest
      description: >-
        Swap one token held in the Credit Account for another, in a single

        atomic transaction, at a firm quote where one covers the pair and at
        market

        rate otherwise.
      default:
        owner: '0x06A9aF046187895AcFc7258450B15397CAc67400'
        chain: base
        token_in: USDC
        token_out: USDT
        amount_in: '0.01'
        slippage: '0.5'
        gas_sponsorship: false
        pricing: auto
    CreditSwapResponse:
      properties:
        transaction:
          anyOf:
            - $ref: '#/components/schemas/UnsignedTransaction'
            - type: 'null'
          description: >-
            Unsigned transaction for direct execution. Present when
            gas_sponsorship=false — except firm-priced previews (preview=true
            responses reporting swap_provider='firm'), which carry the estimate
            only: the firm quote is fetched at execution time, so there is no
            payload to sign yet. A preview whose response reports
            swap_provider='market' does carry this signable payload.
        eip_712:
          anyOf:
            - $ref: '#/components/schemas/BatchedSafeOperationsResponse-Output'
            - type: 'null'
          description: >-
            EIP-712 typed data for gas-sponsored execution. Present when
            gas_sponsorship=true.
        estimated_amount_out:
          type: string
          pattern: ^(?!^[-+.]*$)[+-]?0*\d*\.?\d*$
          title: Estimated Amount Out
          description: >-
            Estimated amount of output token received from the swap. Exact on
            executable firm builds (a firm quote fills at this amount or
            reverts). On market builds it is a quote-time estimate, and
            `slippage` sets how far below it the transaction's enforced minimum
            output sits. On preview=true responses reporting 'firm' it is
            INDICATIVE — computed from the firm provider's live price levels
            without spending a quote.
        swap_provider:
          type: string
          enum:
            - market
            - firm
          title: Swap Provider
          description: >-
            Identifies which route priced the swap. 'market': a DEX aggregator,
            slippage-bounded. 'firm': a zero-slippage quote that fills exactly
            or reverts. On preview=true responses 'firm' means the estimate is
            INDICATIVE, computed from live maker price levels without spending
            any quote; execution fetches the firm quote at signing time. Always
            present. This is the authoritative firm-vs-market signal and clients
            do need to read it: `pricing` is only what was REQUESTED, and under
            'auto' a firm build can fall back to market transparently.
          default: market
        quote_expires_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Quote Expires At
          description: >-
            Deadline of the firm swap quote. Sign and broadcast before it or the
            transaction reverts on-chain; refresh by re-calling this endpoint
            (discard the previous payload). Null on market builds and on every
            preview (a preview never holds a firm quote).
      type: object
      required:
        - estimated_amount_out
      title: CreditSwapResponse
      description: |-
        The swap transaction to sign, plus which route priced it and how long
        that price holds.
      example:
        estimated_amount_out: '2485.123456'
        swap_provider: market
        transaction:
          chainId: '0x2105'
          data: >-
            0x8d80ff0a0000000000000000000000000000000000000000000000000000000000000020
          from: '0x4A83b4413CF41C3244027e1590E35a0F48403F0c'
          gas: '0x7a120'
          maxFeePerGas: '0x59682f00'
          maxPriorityFeePerGas: '0x3b9aca00'
          nonce: '0x5'
          to: '0x6B90E8B4E3E971E74C1A47a3a20976377E2dB4b1'
          value: '0x0'
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    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
    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.
    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).

````