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

# Credit

> Credit lets your users borrow against their crypto holdings through DeFi lending protocols.

## Why This Matters

Building a borrowing product from scratch means integrating with lending protocols, managing collateral ratios, handling swaps, tracking positions across chains, and ongoing maintenance. We've done that - you get one API that covers everything to get your credit product live in days.

## What It Does

Let users borrow stablecoins and other assets against their crypto holdings through Aave. Build products that offer over-collateralised loans, manage collateral positions, and handle liquidation risk - all through a single API.

You call our API, we return a transaction payload. You or your users sign and broadcast. Users access credit, you capture fees.

**Important:** Users must first create a [Credit Account](/v2/Products/Accounts) before borrowing or managing credit positions. Each wallet address gets one Credit Account per chain.

## How It Works

The Credit API bundles multiple DeFi actions into single atomic transactions. A borrow operation can include a swap (if the input token differs from the collateral token), a collateral supply, and a borrow - all in one transaction. Repayments work the same way in reverse.

| Protocol    | What it does                                                   |
| ----------- | -------------------------------------------------------------- |
| **Aave V3** | Lending and borrowing with variable interest rates             |
| **1inch**   | Automatic token swaps when input token differs from collateral |
| **Permit2** | Gasless token transfers from EOA to Credit Account             |

We support Ethereum, Base, and Arbitrum. All operations go through the user's Credit Account (an isolated on-chain account).

## Getting Started

### 1. Create a Credit Account

Before using any credit features, create a Credit Account. This deploys an isolated on-chain account controlled by the user's wallet.

<CodeGroup>
  ```python Python theme={"system"}
  import httpx

  response = httpx.post(
      "https://api.compasslabs.ai/v2/credit/create_account",
      json={
          "chain": "base",
          "sender": "0xYourWalletAddress",
          "owner": "0xYourWalletAddress",
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  result = response.json()

  # result["credit_account_address"] - the deterministic address of the credit account
  # result["transaction"] - unsigned tx to deploy (null if already deployed)
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/create_account",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "YOUR_API_KEY",
      },
      body: JSON.stringify({
        chain: "base",
        sender: "0xYourWalletAddress",
        owner: "0xYourWalletAddress",
      }),
    }
  );
  const result = await response.json();

  // result.credit_account_address - the deterministic address of the credit account
  // result.transaction - unsigned tx to deploy (null if already deployed)
  ```
</CodeGroup>

The account address is deterministic - calling create twice for the same owner and chain returns the same address with `transaction: null` on the second call.

### 2. Fund the Credit Account

Transfer tokens from the user's wallet (EOA) into their Credit Account using the `/v2/credit/transfer` endpoint.

<CodeGroup>
  ```python Python theme={"system"}
  # Deposit 1000 USDC into Credit Account
  response = httpx.post(
      "https://api.compasslabs.ai/v2/credit/transfer",
      json={
          "owner": "0xYourWalletAddress",
          "chain": "base",
          "token": "USDC",
          "amount": "1000",
          "action": "DEPOSIT",
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  result = response.json()

  # result["transaction"] - unsigned ERC-20 transfer tx
  # Sign and broadcast this transaction
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/transfer",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "YOUR_API_KEY",
      },
      body: JSON.stringify({
        owner: "0xYourWalletAddress",
        chain: "base",
        token: "USDC",
        amount: "1000",
        action: "DEPOSIT",
      }),
    }
  );
  const result = await response.json();

  // result.transaction - unsigned ERC-20 transfer tx
  // Sign and broadcast this transaction
  ```
</CodeGroup>

With `gas_sponsorship: true`, the response returns EIP-712 typed data (a Permit2 signature) instead of an unsigned transaction - the user signs off-chain and a gas sponsor executes the transfer.

### 3. Borrow Against Collateral

Supply collateral and borrow in a single atomic transaction. If your input token differs from the collateral token, a swap is performed automatically via 1inch.

<CodeGroup>
  ```python Python theme={"system"}
  # Supply 1000 USDC as collateral and borrow 0.5 WETH
  response = httpx.post(
      "https://api.compasslabs.ai/v2/credit/borrow",
      json={
          "owner": "0xYourWalletAddress",
          "chain": "base",
          "token_in": "USDC",
          "amount_in": "1000",
          "collateral_token": "USDC",
          "borrow_token": "WETH",
          "borrow_amount": "0.5",
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  result = response.json()

  # result["transaction"] - unsigned tx that bundles supply + borrow
  # Sign and broadcast this transaction
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/borrow",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "YOUR_API_KEY",
      },
      body: JSON.stringify({
        owner: "0xYourWalletAddress",
        chain: "base",
        token_in: "USDC",
        amount_in: "1000",
        collateral_token: "USDC",
        borrow_token: "WETH",
        borrow_amount: "0.5",
      }),
    }
  );
  const result = await response.json();

  // result.transaction - unsigned tx that bundles supply + borrow
  // Sign and broadcast this transaction
  ```
</CodeGroup>

**Borrow-only mode:** Omit `token_in`, `amount_in`, and `collateral_token` to borrow against existing collateral without supplying more.

### 4. Repay Debt

Repay borrowed assets and optionally withdraw collateral in a single atomic transaction.

<CodeGroup>
  ```python Python theme={"system"}
  # Repay 0.5 WETH and withdraw 1000 USDC collateral
  response = httpx.post(
      "https://api.compasslabs.ai/v2/credit/repay",
      json={
          "owner": "0xYourWalletAddress",
          "chain": "base",
          "repay_token": "WETH",
          "repay_amount": "0.5",
          "withdraw_token": "USDC",
          "withdraw_amount": "1000",
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  result = response.json()

  # result["transaction"] - unsigned tx that bundles repay + withdraw
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/repay",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "YOUR_API_KEY",
      },
      body: JSON.stringify({
        owner: "0xYourWalletAddress",
        chain: "base",
        repay_token: "WETH",
        repay_amount: "0.5",
        withdraw_token: "USDC",
        withdraw_amount: "1000",
      }),
    }
  );
  const result = await response.json();

  // result.transaction - unsigned tx that bundles repay + withdraw
  ```
</CodeGroup>

**Repay-only mode:** Omit `withdraw_token` and `withdraw_amount` to repay debt without withdrawing collateral.

**Swap on withdrawal:** Set `token_out` to a different token than `withdraw_token` to automatically swap the withdrawn collateral via 1inch.

## Track Positions

### Positions

Get the full state of a Credit Account including collateral, debt, health factor, and borrowable tokens.

<CodeGroup>
  ```python Python theme={"system"}
  response = httpx.get(
      "https://api.compasslabs.ai/v2/credit/positions",
      params={
          "chain": "base",
          "owner": "0xYourWalletAddress",
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  positions = response.json()

  print(f"Health Factor: {positions['account_summary']['health_factor']}")
  print(f"Collateral: ${positions['account_summary']['total_collateral_usd']}")
  print(f"Debt: ${positions['account_summary']['total_debt_usd']}")

  for pos in positions["collateral_positions"]:
      print(f"  Collateral: {pos['symbol']}: {pos['amount_supplied']} (APY: {pos['supply_apy']}%)")

  for pos in positions["debt_positions"]:
      print(f"  Debt: {pos['symbol']}: {pos['amount_borrowed']} (APY: {pos['borrow_apy']}%)")
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/positions?chain=base&owner=0xYourWalletAddress",
    {
      headers: { "x-api-key": "YOUR_API_KEY" },
    }
  );
  const positions = await response.json();

  console.log(`Health Factor: ${positions.account_summary.health_factor}`);
  console.log(`Collateral: $${positions.account_summary.total_collateral_usd}`);
  console.log(`Debt: $${positions.account_summary.total_debt_usd}`);

  for (const pos of positions.collateral_positions) {
    console.log(`Collateral: ${pos.symbol}: ${pos.amount_supplied} (APY: ${pos.supply_apy}%)`);
  }
  for (const pos of positions.debt_positions) {
    console.log(`Debt: ${pos.symbol}: ${pos.amount_borrowed} (APY: ${pos.borrow_apy}%)`);
  }
  ```
</CodeGroup>

The response includes:

| Field                     | Description                                                                                                  |
| ------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **account\_summary**      | Health factor, total collateral/debt in USD, LTV, available borrow capacity, E-Mode status                   |
| **collateral\_positions** | Per-reserve: token, amount, USD value, supply APY, total deposited/withdrawn, interest earned, event history |
| **debt\_positions**       | Per-reserve: token, amount, USD value, borrow APY, total borrowed/repaid, interest paid, event history       |
| **borrowable\_tokens**    | All tokens available to borrow with max borrowable amounts and current APYs                                  |

### Health Factor

The health factor indicates how close an account is to liquidation:

* **> 1.5** — Healthy position with comfortable buffer
* **1.0 - 1.5** — Getting risky, consider adding collateral or repaying debt
* **\< 1.0** — Eligible for liquidation

<Warning>
  If the health factor drops below 1, the position can be liquidated by anyone on-chain. Monitor this value and alert users when it approaches dangerous levels.
</Warning>

### Balances

Use `/v2/credit/balances` to get token balances held in the Credit Account along with transfer history. Takes the same `chain` and `owner` query parameters as the positions endpoint.

## Advanced: Bundle Actions

Compose multiple credit operations into a single atomic transaction using the `/v2/credit/bundle` endpoint. This is also how you supply collateral independently — use the `CREDIT_SUPPLY` action to add collateral without borrowing, or combine it with other actions.

Supported action types:

| Action Type                  | Description                              |
| ---------------------------- | ---------------------------------------- |
| `CREDIT_SUPPLY`              | Supply tokens as collateral to Aave      |
| `CREDIT_WITHDRAW`            | Withdraw collateral from Aave            |
| `CREDIT_BORROW`              | Borrow tokens against collateral         |
| `CREDIT_REPAY`               | Repay outstanding debt                   |
| `CREDIT_ENABLE_COLLATERAL`   | Enable a token as collateral in Aave     |
| `V2_SWAP`                    | Swap tokens within the Credit Account    |
| `V2_TRANSFER_FROM_EOA`       | Pull tokens from EOA into Credit Account |
| `V2_TRANSFER_TO_EOA`         | Send tokens from Credit Account to EOA   |
| `CREDIT_TRANSFER_TO_ADDRESS` | Send tokens to any address               |

<CodeGroup>
  ```python Python theme={"system"}
  # Supply collateral, borrow, and transfer out - all in one tx
  response = httpx.post(
      "https://api.compasslabs.ai/v2/credit/bundle",
      json={
          "owner": "0xYourWalletAddress",
          "chain": "base",
          "actions": [
              {
                  "body": {
                      "action_type": "CREDIT_SUPPLY",
                      "token": "USDC",
                      "amount": "1000",
                  }
              },
              {
                  "body": {
                      "action_type": "CREDIT_BORROW",
                      "token": "WETH",
                      "amount": "0.5",
                  }
              },
              {
                  "body": {
                      "action_type": "V2_TRANSFER_TO_EOA",
                      "token": "WETH",
                      "amount": "0.5",
                  }
              },
          ],
      },
      headers={"x-api-key": "YOUR_API_KEY"},
  )
  result = response.json()

  # result["transaction"] - one tx that does all three actions atomically
  # result["actions_count"] - number of bundled actions (3)
  ```

  ```typescript TypeScript theme={"system"}
  const response = await fetch(
    "https://api.compasslabs.ai/v2/credit/bundle",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-api-key": "YOUR_API_KEY",
      },
      body: JSON.stringify({
        owner: "0xYourWalletAddress",
        chain: "base",
        actions: [
          {
            body: {
              action_type: "CREDIT_SUPPLY",
              token: "USDC",
              amount: "1000",
            },
          },
          {
            body: {
              action_type: "CREDIT_BORROW",
              token: "WETH",
              amount: "0.5",
            },
          },
          {
            body: {
              action_type: "V2_TRANSFER_TO_EOA",
              token: "WETH",
              amount: "0.5",
            },
          },
        ],
      }),
    }
  );
  const result = await response.json();

  // result.transaction - one tx that does all three actions atomically
  // result.actions_count - number of bundled actions (3)
  ```
</CodeGroup>

All bundle endpoints support `gas_sponsorship: true` for gasless execution.

## Use Cases

**Crypto-Backed Loans:** Build a lending product where users deposit ETH or stablecoins as collateral and borrow against it. Show health factor, interest rates, and liquidation warnings in your UI.

*Example: User deposits 10,000 USDC as collateral and borrows 0.5 WETH at 3.2% APY. You embed a fee on each borrow transaction.*

**Leverage Trading:** Let users borrow assets to increase exposure. Deposit collateral, borrow stablecoins, swap to the desired asset - all bundled in a single atomic transaction.

*Example: User deposits 2 ETH, borrows 5,000 USDC, swaps to more ETH for leveraged long exposure.*

**Margin for Global Markets:** Combine Credit with [Global Markets](/v2/Products/Global-Markets). Users borrow USDC against crypto collateral, then use it to trade stock perps.

*Example: User deposits 10,000 USDC as collateral, borrows 5,000 USDC, deposits it to trade AAPL and NVDA perps on Hyperliquid.*

## Next Steps

<CardGroup cols={3}>
  <Card title="Product Accounts" icon="wallet" href="/v2/Products/Accounts">
    Learn more about how Credit Accounts work.
  </Card>

  <Card title="Earn" icon="chart-line" href="/v2/Products/Earn">
    Earn yield on idle assets while using them as collateral.
  </Card>

  <Card title="Gas Sponsorship" icon="gas-pump" href="/v2/Products/gas-sponsorship">
    Sponsor gas for your users so they never need ETH.
  </Card>
</CardGroup>
