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

# Settle Liquidation

> Route sale proceeds back to the market and close the liquidation

Closes a liquidation by forwarding the cumulative proceeds from the router to the lending market. This repays the pool, pays any surplus to the borrower, and marks the record `SETTLED`.

This is the final step of the manual settlement workflow. Until it is called, the liquidated debt remains outstanding on the market and counts against `pendingLiquidationDebt`.

## Path Parameters

<ParamField path="liquidationId" type="string" required>
  Liquidation ID on the market's router.
</ParamField>

## Body Parameters

<ParamField body="marketId" type="string">
  Names the market whose liquidation you mean. Every market runs its own liquidation router and IDs restart at `1` on each of them, so the same `liquidationId` can exist on several markets in one instance. Supply this when it does, otherwise the call is refused with `AMBIGUOUS_LIQUIDATION_ID` and the response lists the candidates. Also accepted as a query parameter.
</ParamField>

<ParamField body="usdcProceeds" type="string" required>
  Final proceeds to deposit before settling, in the market's borrow asset. Must be zero or greater.

  Send the full sale proceeds when settling in one step. Send `"0"` when the proceeds were already deposited through [Report Partial Sale](/endpoints/lending/report-partial-sale), and the router forwards what it already holds.
</ParamField>

<ParamField body="txHash" type="string">
  Hash of the transaction you broadcast for this operation. Send it to confirm the transaction and record the result. Omit it to receive the calldata.
</ParamField>

<Note>
  The signing wallet must hold `OPERATOR_ROLE` on the router. If it does not, the calldata is not returned: the response carries `ROUTER_OPERATOR_ROLE_MISSING` along with the `calldata` that grants the role. When `usdcProceeds` is greater than zero that wallet must also hold the proceeds, since settlement pulls them from it.
</Note>

## Response Fields

<ResponseField name="data" type="object">
  <Expandable>
    <ResponseField name="liquidationId" type="string">Liquidation ID, echoed back.</ResponseField>
    <ResponseField name="success" type="boolean">Nested inside `data` on the calldata response.</ResponseField>
    <ResponseField name="action" type="string">`SIGN_TRANSACTIONS`. Returned when `txHash` is omitted.</ResponseField>
    <ResponseField name="steps" type="array">Ordered `approve` on the borrow asset, then `settleLiquidation`. Returned when `txHash` is omitted. The approve step is omitted when `usdcProceeds` is zero, leaving `settleLiquidation` as the only step.</ResponseField>
    <ResponseField name="usdcProceeds" type="string">Proceeds the router actually forwarded to the market, read from the settlement event rather than from the request. Returned when confirming with `txHash`.</ResponseField>
    <ResponseField name="txHash" type="string">Transaction hash. Returned when confirming with `txHash`.</ResponseField>
  </Expandable>
</ResponseField>

## Proceeds Distribution

The market keeps at most the liquidated debt plus the market's `liquidationPenalty`. Anything above that is surplus and belongs to the borrower.

Surplus is pushed directly to the borrower's wallet. If the settlement token (stablecoin) rejects that transfer on compliance grounds, the amount is escrowed on the market contract against the borrower's address instead of reverting the settlement, and the borrower claims it later. Settlement therefore always completes, whether or not the borrower can currently receive funds.

When proceeds fall short of the debt, the shortfall is recorded as slippage on the settlement event. The pool absorbs the loss. It is not automatically covered by the insurance fund, which only steps in on a timeout write-off.

<Warning>
  Settling with zero proceeds is rejected with `NO_PROCEEDS_COLLECTED` unless the router already holds proceeds from a reported partial sale. This prevents accidentally closing a liquidation that recovered nothing, which would silently write off the debt against the pool.
</Warning>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.trusset.org/lending-external-securities/api/liquidations/settle/14" \
    -H "X-API-Key: trusset_your_key_here" \
    -H "Content-Type: application/json" \
    -d '{"usdcProceeds": "21400.00"}'
  ```

  ```typescript TypeScript theme={null}
  const res = await fetch(
    `https://api.trusset.org/lending-external-securities/api/liquidations/settle/${liquidationId}`,
    {
      method: 'POST',
      headers: {
        'X-API-Key': 'trusset_your_key_here',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ usdcProceeds: '21400.00' })
    }
  );
  const { success, data, error } = await res.json();
  ```
</RequestExample>

<ResponseExample>
  ```json Confirmed Response theme={null}
  {
    "success": true,
    "data": {
      "liquidationId": "14",
      "usdcProceeds": "21400.000000",
      "txHash": "0x9f2c41d8b7e05a3164c2870fbd935e1a4c7802db6135ea9048f7c21b5d3ea41b"
    }
  }
  ```

  ```json Error - Ambiguous ID theme={null}
  {
    "success": false,
    "error": {
      "code": "AMBIGUOUS_LIQUIDATION_ID",
      "message": "Liquidation 14 exists on 2 markets in this instance because every market runs its own liquidation router. Pass marketId to name the one you mean.",
      "candidates": [
        {
          "marketId": "clx_secmarket_001",
          "marketAddress": "0x70a0e25c7b768b87e658348b3b577678a173e038",
          "status": "PENDING",
          "collateralAmount": "220.000000000000000000"
        },
        {
          "marketId": "clx_secmarket_004",
          "marketAddress": "0x1c74f9a2b0e63d581a47c02f9b8de3517a604c2b",
          "status": "WITHDRAWN_TO_CUSTODY",
          "collateralAmount": "85.000000000000000000"
        }
      ]
    }
  }
  ```

  ```json Error - Nothing Collected theme={null}
  {
    "success": false,
    "error": {
      "code": "NO_PROCEEDS_COLLECTED",
      "message": "No proceeds have been collected for this liquidation"
    }
  }
  ```

  ```json Error - Already Settled theme={null}
  {
    "success": false,
    "error": {
      "code": "ALREADY_SETTLED",
      "message": "Already settled or written off"
    }
  }
  ```
</ResponseExample>

## Error Codes

| Code                           | HTTP  | Cause                                                                                                           |
| ------------------------------ | ----- | --------------------------------------------------------------------------------------------------------------- |
| `MISSING_ID`                   | `400` | No liquidation ID in the path                                                                                   |
| `INVALID_AMOUNT`               | `400` | `usdcProceeds` is absent, non-numeric, or negative                                                              |
| `AMBIGUOUS_LIQUIDATION_ID`     | `400` | This ID exists on more than one market in your instance. The error carries `candidates`; resend with `marketId` |
| `ALREADY_SETTLED`              | `400` | The liquidation is already settled or written off                                                               |
| `NO_PROCEEDS_COLLECTED`        | `400` | Zero was submitted and the router holds no proceeds                                                             |
| `WALLET_NOT_CONFIGURED`        | `400` | No verified wallet is registered on this instance to resolve the signer against                                 |
| `ROUTER_OPERATOR_ROLE_MISSING` | `400` | The resolved wallet lacks `OPERATOR_ROLE`. The error carries grant `calldata`                                   |
| `ROUTER_NOT_CONFIGURED`        | `400` | No liquidation router resolved for this market                                                                  |
| `TX_NOT_VERIFIED`              | `400` | The confirmed transaction settles a different liquidation                                                       |
| `SETTLE_TX_REVERTED`           | `400` | The settlement reverted. `error.txHash` carries the hash when one exists                                        |
| `LIQUIDATION_NOT_FOUND`        | `404` | No liquidation with that ID on your instance, and none could be adopted from chain                              |
| `MARKET_NOT_FOUND`             | `404` | `marketId` was supplied but names no market on your instance                                                    |
