# Bidding on Liquidations

### Overview

When Credit Account positions become undercollateralized, their collateral is sold through RUJI Trade orderbooks. Users can place [**tracking orders**](#ruji-trade-tracking-orders) at a discount to the current oracle price (defined by [THORChain enshrined oracle](https://dev.thorchain.org/bifrost/oracle.html)). When liquidations route through these orders, users acquire collateral at their specified discount.

#### How It Works

```
1. User places order: "Buy BTC at 5% below oracle price"
   └─> Order sits in RUJI Trade orderbook

2. Borrower's position becomes liquidatable
   └─> Liquidation solver executes liquidation

3. Solver swaps collateral (BTC) for debt token (USDC) via a market order on RUJI Trade
   └─> If the market order creates a large enough wick, the order gets filled at 5% discount

4. User withdraws filled order
   └─> Receives BTC acquired at discounted price
```

#### Key Benefits

* **No active monitoring** - Set orders and wait
* **Guaranteed discount** - Only fills at your specified discount to market price, typically at the local low as this is when liquidations tend to happen
* **Pro-rata fills** - Fair distribution when multiple bidders at same price
* **Flexibility** - Withdraw unfilled orders anytime

***

### RUJI Trade Tracking Orders

**Tracking orders** track the oracle price with a basis point adjustment:

* `{ "oracle": 0 }` = Exactly at oracle price
* `{ "oracle": -100 }` = Oracle price minus 1% (100 bps)
* `{ "oracle": -500 }` = Oracle price minus 5% (500 bps)
* `{ "oracle": 100 }` = Oracle price plus 1%

***

### Placing Liquidation Bids

#### Order Message Structure

```typescript
const executeMsg = {
  order: [
    // Array of order targets
    [
      ["quote", { "oracle": -500 }, "100000000000"]  // [side, price, amount]
    ],
    null  // Optional callback
  ]
};
```

#### Parameters

| Field    | Type                  | Description                                       |
| -------- | --------------------- | ------------------------------------------------- |
| `side`   | `"base"` or `"quote"` | Which token you're offering                       |
| `price`  | `"oracle":` `integer` | Price expressed as a deviation from Oracle in bps |
| `amount` | `Uint128` or `null`   | Target amount (`null` = withdraw all)             |

#### Side Explanation

For a BTC/USDC pair:

* **Base** = BTC (first token)
* **Quote** = USDC (second token)

To **buy BTC at a discount** (typical liquidation bid on the long side):

* Side: `"quote"` (you're offering USDC)
* Price: `{ "oracle": -500 }` (5% below oracle)
* You receive BTC when filled

To **sell BTC at a premium** (to liquidate a position on the short side):

* Side: `"base"` (you're offering BTC)
* Price: `{ "oracle": 500 }` (5% above oracle)

***

### Code Examples

#### Place a Bid (TypeScript)

```typescript
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const FIN_BTC_USDC = "<FIN_BTC_USDC_ADDRESS>";

async function placeLiquidationBid(
  client: SigningCosmWasmClient,
  sender: string,
  usdcAmount: string,
  discountBps: number  // e.g., 500 for 5% discount
) {
  const executeMsg = {
    order: [
      [
        // Buy BTC at X% discount to oracle
        ["quote", { oracle: -discountBps }, usdcAmount]
      ],
      null
    ]
  };

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    [{ denom: "usdc", amount: usdcAmount }]
  );
}

// Place 1000 USDC bid at 5% discount
await placeLiquidationBid(client, myAddress, "100000000000", 500);
```

#### Query Your Orders

```typescript
const queryMsg = {
  orders: {
    owner: myAddress
  }
};

const orders = await client.queryContractSmart(FIN_BTC_USDC, queryMsg);
console.log(orders);
```

**Response:**

```json
{
  "orders": [
    {
      "side": "quote",
      "price": { "oracle": -500 },
      "offer": "100000000000",
      "filled": "25000000000",
      "created_at": "1703001600000000000"
    }
  ]
}
```

#### Withdraw Filled Orders

```typescript
async function withdrawFilledOrders(
  client: SigningCosmWasmClient,
  sender: string
) {
  // Setting amount to null withdraws all filled amounts
  const executeMsg = {
    order: [
      [
        ["quote", { oracle: -500 }, null]  // null = withdraw
      ],
      null
    ]
  };

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto"
  );
}
```

#### Modify Order Amount

```typescript
async function modifyBid(
  client: SigningCosmWasmClient,
  sender: string,
  newAmount: string,
  currentAmount: string,
  discountBps: number
) {
  const executeMsg = {
    order: [
      [
        ["quote", { oracle: -discountBps }, newAmount]
      ],
      null
    ]
  };

  // Calculate net change in funds
  const diff = BigInt(newAmount) - BigInt(currentAmount);

  const funds = diff > 0n
    ? [{ denom: "usdc", amount: diff.toString() }]
    : [];

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    funds
  );
}
```

***

### Multiple Orders at Different Discounts

Place a ladder of bids at various discount levels:

```typescript
async function placeBidLadder(
  client: SigningCosmWasmClient,
  sender: string
) {
  const executeMsg = {
    order: [
      [
        // 3% discount - highest priority, fills first
        ["quote", { oracle: -300 }, "30000000000"],
        // 5% discount
        ["quote", { oracle: -500 }, "40000000000"],
        // 10% discount - fills only in severe liquidations
        ["quote", { oracle: -1000 }, "30000000000"]
      ],
      null
    ]
  };

  const totalUsdc = "100000000000";  // 1000 USDC total

  return client.execute(
    sender,
    FIN_BTC_USDC,
    executeMsg,
    "auto",
    "",
    [{ denom: "usdc", amount: totalUsdc }]
  );
}
```

***

### How Orders Get Filled

#### Fill Priority

When liquidations swap collateral, orders are filled by price priority:

1. Orders closest to oracle price fill first
2. At same price level, orders fill **pro-rata** (proportional to size)
3. Tracking orders adjust automatically as oracle price moves

#### Pro-Rata Example

```
Pool at -5% discount has:
- Alice: 1000 USDC (50%)
- Bob:   600 USDC (30%)
- Carol: 400 USDC (20%)

Liquidation swaps 500 USDC worth:
- Alice receives: 250 USDC worth of BTC
- Bob receives:   150 USDC worth of BTC
- Carol receives: 100 USDC worth of BTC
```

#### Bid Pool Mechanics

Orders at the same price level share a **bid pool**. The contract tracks:

* `offer`: Your original USDC amount
* `filled`: Amount converted to BTC
* `product_snapshot`: Used for pro-rata calculation

***

### Fees

| Fee       | Rate   | When                           |
| --------- | ------ | ------------------------------ |
| Maker Fee | 0.075% | On withdrawal of filled orders |
| No fee    | -      | Cancelling unfilled orders     |

> Fee rates are configurable per trading pair. Query the pair config for current values.

***

### Risks and Considerations

#### Market Risk

* Collateral value may drop further after you acquire it
* Oracle price may differ from actual market price

#### Liquidity Risk

* Orders may not fill if liquidations don't occur at your desired discount
* Capital is locked while order is active

#### Timing Risk

* During high volatility, liquidations happen rapidly
* Orders at shallow discounts fill first

#### Recommendations

1. **Diversify discount levels** - Place orders at multiple price points
2. **Monitor positions** - Check filled amounts regularly
3. **Set realistic discounts** - Too deep = rarely fills, too shallow = less profit
4. **Understand the asset** - Only bid on collateral you want to hold

***

### Supported Trading Pairs

Liquidation flow routes through RUJI Trade pairs. Common pairs:

<table><thead><tr><th width="150">Pair</th><th>Contract</th></tr></thead><tbody><tr><td>BTC/USDC</td><td><code>thor1dwsnlqw3lfhamc5dz3r57hlsppx3a2n2d7kppccxfdhfazjh06rs5077sz</code></td></tr><tr><td>ETH/USDC</td><td><code>thor1tnd06uswj8033d0kzd5d7zre73u3uc44r2vvez26z5m4kr68vtusf2snva</code></td></tr><tr><td>BCH/USDC</td><td><code>thor1s4jpxtz0jsh6elyqcdujd303ptefz53gknmcp437rm9ykxnfhysqrm5hze</code></td></tr><tr><td>DOGE/USDC</td><td><code>thor1w8agselh7k2e4ty369v39lngkckljxfafm35d06f7wj3ar90h2esv75t7p</code></td></tr><tr><td>LTC/USDC</td><td><code>thor1ks9qq0nwv7qxtnznesys6ylflwruqlf85er6zls4erwgzkvw0m0qs3rghz</code></td></tr><tr><td>XRP/USDC</td><td><code>thor14v89h32ztmfg9d230cjly7ac26fvdkhgq7nkntsw4uy2f3yh2v7qrz6hsw</code></td></tr></tbody></table>

> **Note:** For the full list of RUJI Trade pairs, check <https://rujira.network/developer/deployment> and look for `rujira-fin`.

***

### Message Reference

#### ExecuteMsg::Order

```json
{
  "order": [
    [
      ["quote", { "oracle": -500 }, "100000000000"],
      ["quote", { "oracle": -1000 }, "50000000000"]
    ],
    null
  ]
}
```

#### QueryMsg::Orders

```json
{
  "orders": {
    "owner": "thor1..."
  }
}
```

#### QueryMsg::Config

```json
{
  "config": {}
}
```

Returns pair configuration including denoms, fees, and oracles.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.rujira.network/developers/ruji-product-integration-guides/ruji-liquidations/bidding-on-liquidations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
