# RUJI Lend & Borrow

### Overview

The RUJI Money Market consists of two core contract types:

| Contract                                 | Purpose                      | User Actions                                     |
| ---------------------------------------- | ---------------------------- | ------------------------------------------------ |
| **Ghost Vault** (`rujira-ghost-vault`)   | Lending pools for each asset | Deposit, Withdraw                                |
| **Ghost Credit** (`rujira-ghost-credit`) | CDP loan management          | Create Account, Borrow, Repay, Manage Collateral |

#### Architecture

```
┌─────────────────┐     ┌─────────────────┐
│   Ghost Vault   │     │   Ghost Vault   │
│      (BTC)      │     │     (USDC)      │  ... per asset
└────────┬────────┘     └────────┬────────┘
         │                       │
         │    Borrows from       │
         ▼                       ▼
┌─────────────────────────────────────────┐
│            Ghost Credit                 │
│  (Manages Credit Accounts / CDPs)       │
└─────────────────────────────────────────┘
                    │
                    │ Creates
                    ▼
┌─────────────────────────────────────────┐
│          Credit Account                 │
│   (User's isolated margin account)      │
│   - Holds collateral                    │
│   - Tracks debt positions               │
└─────────────────────────────────────────┘
```

***

### Contract Addresses

#### Mainnet

<table><thead><tr><th width="180">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>thor1ekkt8wfls055t7f7yznj07j0s4mtndkq546swutzv2de7sfcxptq27duyt</code></td></tr><tr><td>Ghost Vault (BTC)</td><td><code>thor18e6gxcvmqfn06l09gurgwh3urlj9xztqagaslgspl2l74ejuujnqqlzzun</code></td></tr><tr><td>Ghost Vault (ETH)</td><td><code>thor1xufzny7n3565jy3rvglacengpn6eufw7lk5y9h4zxludkfe96q4s9j5uln</code></td></tr><tr><td>Ghost Vault (USDC)</td><td><code>thor1hs6wzyk4tf25ujd7lu07hhnkj4tl38m3wpp6qqw50y5r3e3x7zksnvj3qr</code></td></tr><tr><td>Ghost Vault (USDT)</td><td><code>thor1smdzjdm5q5e5kf6farvcgmxe44uhga2ety68veu2nupf5dzx55xsn3u4rj</code></td></tr><tr><td>Ghost Vault (BCH)</td><td><code>thor1km2sgadhmev34v40evf8qh2yw77hxecakn9nu0g35zdtsf905ehqhqk76r</code></td></tr><tr><td>Ghost Vault (DOGE)</td><td><code>thor1drfu6vrn06gam7fdk07xqmavthgy6rnmnmm2mh4fa047qsny52aqvxuck9</code></td></tr><tr><td>Ghost Vault (LTC)</td><td><code>thor1633kq6mxwn24ezdn38xpngksx8wlu458yesdqf3xhs2cfaan96cs2c3gdz</code></td></tr><tr><td>Ghost Vault (XRP)</td><td><code>thor1cvry7e7uzd89dv4hls5rg5m4xykczzu2qvj8dq5e93c75566tk9q7cya3l</code></td></tr></tbody></table>

> **Note:** For the full list of lending vaults, check <https://rujira.network/developer/deployment> and look for `rujira-ghost-vault`.

#### Stagenet (Testnet)

<table><thead><tr><th width="180">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Ghost Credit</td><td><code>sthor16p65kngn6wtyxrngh2fkwtth4lr9eysvq7atsxt9qhnkknanw8yqza6pqa</code></td></tr><tr><td>Ghost Vault (USDT)</td><td><code>sthor165wfwxnw3vrp35h3ttf23vd0zgs3mt34r8rll50qe0jffun5ts8sdjp38e</code></td></tr></tbody></table>

***

### Supported Assets

All amounts use **8 decimal places** (THORChain standard).

<table><thead><tr><th width="111.640625">Asset</th><th>Denom</th><th width="160.9237060546875">Collateral Ratio</th><th>Lending Vault Receipt Token</th></tr></thead><tbody><tr><td>BTC</td><td><code>BTC-BTC</code></td><td>70%</td><td><code>x/ghost-vault/BTC-BTC</code></td></tr><tr><td>ETH</td><td><code>ETH-ETH</code></td><td>70%</td><td><code>x/ghost-vault/ETH-ETH</code></td></tr><tr><td>USDC</td><td><code>ETH-USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48</code></td><td>70%</td><td><code>x/ghost-vault/ETH-USDC-0XA0B86991C6218B36C1D19D4A2E9EB0CE3606EB48</code></td></tr><tr><td>USDT</td><td><code>ETH-USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7</code></td><td>70%</td><td><code>x/ghost-vault/ETH-USDT-0XDAC17F958D2EE523A2206206994597C13D831EC7</code></td></tr><tr><td>BCH</td><td><code>BCH-BCH</code></td><td>70%</td><td><code>x/ghost-vault/BCH-BCH</code></td></tr><tr><td>DOGE</td><td><code>DOGE-DOGE</code></td><td>70%</td><td><code>x/ghost-vault/DOGE-DOGE</code></td></tr><tr><td>LTC</td><td><code>LTC-LTC</code></td><td>70%</td><td><code>x/ghost-vault/LTC-LTC</code></td></tr><tr><td>XRP</td><td><code>XRP-XRP</code></td><td>70%</td><td><code>x/ghost-vault/XRP-XRP</code></td></tr></tbody></table>

> **Note**: Collateral ratios are configurable via governance. Query the Ghost Credit contract configuration (`{"config": {}}`) for full list of supported collaterals and their current collateral ratio values.

***

### Part 1: Lending Integration (Ghost Vault)

Lenders deposit assets into Ghost Vault contracts and receive receipt tokens that **accrue interest over time**.

#### 1.1 Query: Get Vault Status

Returns current rates, utilization, and pool sizes.

```typescript
// Query message
const queryMsg = { status: {} };

// Example using CosmJS
const result = await client.queryContractSmart(
  GHOST_VAULT_BTC_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "last_updated": "1703001600000000000",
  "utilization_ratio": "0.65",
  "debt_rate": "0.08",
  "lend_rate": "0.052",
  "debt_pool": {
    "size": "650000000000",
    "shares": "620000000000",
    "ratio": "1.048387"
  },
  "deposit_pool": {
    "size": "1000000000000",
    "shares": "980000000000",
    "ratio": "1.020408"
  }
}
```

**Field Explanations:**

* `utilization_ratio`: Percentage of deposits currently borrowed (0.65 = 65%)
* `debt_rate`: Annual borrow APR (0.08 = 8%)
* `lend_rate`: Annual supply APY (0.052 = 5.2%)
* `deposit_pool.ratio`: Value of 1 receipt token in underlying asset

#### 1.2 Query: Get Vault Config

Returns the underlying asset denom and interest rate parameters.

```typescript
const queryMsg = { config: {} };
```

**Response:**

```json
{
  "denom": "btc",
  "interest": {
    "target_utilization": "0.8",
    "base_rate": "0.03",
    "step1": "0.1",
    "step2": "2.0"
  }
}
```

#### 1.3 Calculate User Position Value

To display a user's lending position value:

```typescript
// 1. Get user's receipt token balance
const receiptBalance = await client.getBalance(
  userAddress,
  "x/ghost-vault/btc"
);

// 2. Get current pool ratio
const status = await client.queryContractSmart(
  GHOST_VAULT_BTC_ADDRESS,
  { status: {} }
);

// 3. Calculate underlying value
const underlyingValue = BigInt(receiptBalance.amount) *
  BigInt(status.deposit_pool.size) /
  BigInt(status.deposit_pool.shares);
```

#### 1.4 Execute: Deposit

Deposit assets to receive interest-bearing receipt tokens.

```typescript
const executeMsg = {
  deposit: {}
};

const result = await client.execute(
  userAddress,
  GHOST_VAULT_BTC_ADDRESS,
  executeMsg,
  "auto",
  "",
  [{ denom: "btc", amount: "100000000" }] // 1 BTC (8 decimals)
);
```

**What happens:**

1. User sends underlying asset (e.g., BTC)
2. Contract mints receipt tokens based on current `deposit_pool.ratio`
3. Receipt tokens are sent to user's wallet

#### 1.5 Execute: Withdraw

Burn receipt tokens to retrieve underlying assets plus accrued interest.

```typescript
const executeMsg = {
  withdraw: {}
};

const result = await client.execute(
  userAddress,
  GHOST_VAULT_BTC_ADDRESS,
  executeMsg,
  "auto",
  "",
  [{ denom: "x/ghost-vault/btc", amount: "100000000" }]
);
```

**What happens:**

1. User sends receipt tokens
2. Contract burns receipt tokens
3. Underlying asset (including accrued interest) is returned

> **Note**: Withdrawals may fail if utilization is at 100%. The contract ensures liquidity by incentivizing deposits when utilization is high.

***

### Part 2: Borrowing Integration (Ghost Credit)

Borrowers create Credit Accounts, deposit collateral, and borrow against it.

#### 2.1 Query: Get Credit Config

Returns collateral ratios, liquidation thresholds, and fee parameters.

```typescript
const queryMsg = { config: {} };

const config = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "code_id": 123,
  "collateral_ratios": {
    "btc": "0.7",
    "eth": "0.7",
    "usdc": "0.7"
  },
  "fee_liquidation": "0.01",
  "fee_liquidator": "0.005",
  "liquidation_threshold": "1.0",
  "adjustment_threshold": "0.9",
  "liquidation_max_slip": "0.3"
}
```

**Field Explanations:**

* `collateral_ratios`: Maximum borrowing power per collateral type (0.7 = can borrow up to 70% of value)
* `liquidation_threshold`: LTV at which liquidation is triggered (1.0 = 100%)
* `adjustment_threshold`: Maximum LTV users can manually adjust to (0.9 = 90%)
* `fee_liquidation`: Protocol fee on liquidations (1%)
* `fee_liquidator`: Fee paid to liquidation executors (0.5%)

#### 2.2 Query: Get User's Credit Accounts

```typescript
const queryMsg = {
  accounts: {
    owner: "thor1abc..."
  }
};

const accounts = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

**Response:**

```json
{
  "accounts": [
    {
      "owner": "thor1abc...",
      "account": "thor1xyz...",
      "tag": "main",
      "ltv": "0.45",
      "collaterals": [
        {
          "collateral": { "coin": { "denom": "btc", "amount": "100000000" } },
          "value_full": "43000.0",
          "value_adjusted": "30100.0"
        }
      ],
      "debts": [
        {
          "debt": {
            "addr": "thor1xyz...",
            "borrower": { "denom": "usdc", "current": "15000000000" },
            "current": "15000000000",
            "shares": "14500000000"
          },
          "value": "15000.0"
        }
      ],
      "liquidation_preferences": {
        "messages": [],
        "order": { "map": {}, "limit": 100 }
      }
    }
  ]
}
```

**Field Explanations:**

* `account`: The Credit Account contract address (holds collateral)
* `ltv`: Current loan-to-value ratio (debt / adjusted collateral value)
* `value_full`: Full USD value of collateral
* `value_adjusted`: USD value after applying collateral ratio
* `debts[].current`: Current debt amount including accrued interest

#### 2.3 Query: Single Credit Account

```typescript
const queryMsg = {
  account: "thor1xyz..."  // Credit Account address
};
```

#### 2.4 Query: Predict Account Address

Get the deterministic address for a new Credit Account before creation.

```typescript
import { toBase64, toUtf8 } from "@cosmjs/encoding";

const salt = toBase64(toUtf8("my-account-1"));

const queryMsg = {
  predict: {
    owner: "thor1abc...",
    salt: salt
  }
};

const predictedAddress = await client.queryContractSmart(
  GHOST_CREDIT_ADDRESS,
  queryMsg
);
```

#### 2.5 Execute: Create Credit Account

```typescript
import { toBase64, toUtf8 } from "@cosmjs/encoding";

const executeMsg = {
  create: {
    salt: toBase64(toUtf8("unique-salt-123")),
    label: "My BTC Loan",
    tag: "wallet-app"
  }
};

const result = await client.execute(
  userAddress,
  GHOST_CREDIT_ADDRESS,
  executeMsg,
  "auto"
);

// Extract the new account address from events
const accountAddress = result.events
  .find(e => e.type === "wasm-rujira-ghost-credit/create_account")
  ?.attributes.find(a => a.key === "account")?.value;
```

#### 2.6 Execute: Deposit Collateral & Borrow

All Credit Account operations are batched in a single `account` message:

```typescript
const executeMsg = {
  account: {
    addr: "thor1xyz...",  // Credit Account address
    msgs: [
      // First: Send collateral to the account (standard bank send)
      // This is done separately before calling the contract

      // Then: Borrow against collateral
      {
        borrow: {
          denom: "usdc",
          amount: "10000000000"  // 100 USDC
        }
      }
    ]
  }
};
```

**Full flow to deposit collateral and borrow:**

```typescript
// Step 1: Send collateral to Credit Account address
const sendMsg = {
  typeUrl: "/cosmos.bank.v1beta1.MsgSend",
  value: {
    fromAddress: userAddress,
    toAddress: creditAccountAddress,
    amount: [{ denom: "btc", amount: "50000000" }]  // 0.5 BTC
  }
};

// Step 2: Borrow against the collateral
const borrowMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        borrow: {
          denom: "usdc",
          amount: "10000000000"
        }
      }
    ]
  }
};

// Execute both in sequence
await client.signAndBroadcast(userAddress, [sendMsg], "auto");
await client.execute(userAddress, GHOST_CREDIT_ADDRESS, borrowMsg, "auto");
```

#### 2.7 Execute: Repay Debt

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        repay: {
          denom: "usdc",
          amount: "5000000000"  // 50 USDC
        }
      }
    ]
  }
};

// Note: The Credit Account must hold the repayment tokens
// First send USDC to the Credit Account, then call repay
```

#### 2.8 Execute: Withdraw Collateral

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      {
        send: {
          to_address: userAddress,
          funds: [{ denom: "btc", amount: "10000000" }]
        }
      }
    ]
  }
};

// This will fail if it would push LTV above adjustment_threshold
```

#### 2.9 Execute: Close Position (Repay All & Withdraw)

```typescript
const executeMsg = {
  account: {
    addr: creditAccountAddress,
    msgs: [
      // Repay full debt (send slightly more to account for interest)
      { repay: { denom: "usdc", amount: "10050000000" } },
      // Withdraw all collateral
      { send: { to_address: userAddress, funds: [{ denom: "btc", amount: "50000000" }] } }
    ]
  }
};
```

***

### Part 3: Displaying Data in UI

#### 3.1 Lending Position

```typescript
interface LendingPosition {
  asset: string;
  deposited: string;      // Receipt token balance
  depositedValue: string; // Underlying value
  apy: string;            // Current lend rate
}

async function getLendingPosition(
  userAddress: string,
  vaultAddress: string,
  denom: string
): Promise<LendingPosition | null> {
  const receiptDenom = `x/ghost-vault/${denom}`;
  const balance = await client.getBalance(userAddress, receiptDenom);

  if (BigInt(balance.amount) === 0n) {
    return null;
  }

  const status = await client.queryContractSmart(vaultAddress, { status: {} });

  const underlyingValue = BigInt(balance.amount) *
    BigInt(status.deposit_pool.size) /
    BigInt(status.deposit_pool.shares);

  return {
    asset: denom.toUpperCase(),
    deposited: balance.amount,
    depositedValue: underlyingValue.toString(),
    apy: (parseFloat(status.lend_rate) * 100).toFixed(2) + "%"
  };
}
```

#### 3.2 Borrow Position

```typescript
interface BorrowPosition {
  accountAddress: string;
  collaterals: Array<{
    asset: string;
    amount: string;
    valueUsd: string;
  }>;
  debts: Array<{
    asset: string;
    amount: string;
    valueUsd: string;
  }>;
  ltv: string;
  healthFactor: string;  // 1 / ltv (higher is safer)
}

function parseBorrowPosition(accountResponse: any): BorrowPosition {
  return {
    accountAddress: accountResponse.account,
    collaterals: accountResponse.collaterals.map(c => ({
      asset: c.collateral.coin.denom.toUpperCase(),
      amount: c.collateral.coin.amount,
      valueUsd: c.value_full
    })),
    debts: accountResponse.debts.map(d => ({
      asset: d.debt.borrower.denom.toUpperCase(),
      amount: d.debt.current,
      valueUsd: d.value
    })),
    ltv: (parseFloat(accountResponse.ltv) * 100).toFixed(2) + "%",
    healthFactor: (1 / parseFloat(accountResponse.ltv)).toFixed(2)
  };
}
```

#### 3.3 Risk Indicators

Display clear risk levels based on LTV:

| LTV Range  | Health Status | Color          |
| ---------- | ------------- | -------------- |
| 0% - 50%   | Safe          | Green          |
| 50% - 75%  | Moderate      | Yellow         |
| 75% - 90%  | At Risk       | Orange         |
| 90% - 100% | Danger        | Red            |
| > 100%     | Liquidatable  | Red (flashing) |

***

### Part 4: Interest Rate Model

The protocol uses a kinked interest rate model:

```
borrow_rate = base_rate + (utilization / target) * step1           [if utilization <= target]
borrow_rate = base_rate + step1 + ((util - target) / (1 - target)) * step2  [if utilization > target]
```

#### Example Calculation

With parameters: `base_rate=3%`, `target=80%`, `step1=10%`, `step2=200%` , `fee=10%`

| Utilization | Borrow Rate | Supply Rate |
| ----------- | ----------- | ----------- |
| 0%          | 3.0%        | 0.0%        |
| 40%         | 8.0%        | 2.9%        |
| 80%         | 13.0%       | 9.4%        |
| 90%         | 113.0%      | 91.5%       |
| 100%        | 213.0%      | 191.7%      |

> **Supply Rate** = Borrow Rate × Utilization × (1 - Protocol Fee)

***

### Part 5: Fees

#### Protocol Fees

| Fee Type        | Rate                   | Distribution                |
| --------------- | ---------------------- | --------------------------- |
| Interest Fee    | 10% of borrow interest | 50% Protocol, 50% THORChain |
| Liquidation Fee | 1% of repaid debt      | 50% Protocol, 50% THORChain |
| Liquidator Fee  | 0.5% of repaid debt    | Liquidation executor        |

> Fee parameters are configurable via governance. Query contract config for current values.

***

### Part 6: Error Handling

#### Common Errors

| Error               | Cause                             | Solution                               |
| ------------------- | --------------------------------- | -------------------------------------- |
| `Unauthorized`      | Not the account owner             | Verify sender matches account owner    |
| `Unsafe`            | Operation would exceed LTV limit  | Reduce borrow amount or add collateral |
| `ZeroDebt`          | Repaying when no debt exists      | Check debt balance first               |
| `InvalidCollateral` | Asset not in collateral whitelist | Use only supported collateral types    |

#### Transaction Simulation

Always simulate transactions before broadcasting:

```typescript
try {
  const simResult = await client.simulate(
    userAddress,
    [executeMsg],
    ""
  );
  console.log("Estimated gas:", simResult);
} catch (error) {
  console.error("Transaction would fail:", error.message);
}
```

***

### Part 7: Code Examples

#### Complete Lending Flow (TypeScript)

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

const GHOST_VAULT_BTC = "<GHOST_VAULT_BTC_ADDRESS>";

async function deposit(
  client: SigningCosmWasmClient,
  sender: string,
  amount: string
) {
  return client.execute(
    sender,
    GHOST_VAULT_BTC,
    { deposit: {} },
    "auto",
    "",
    [{ denom: "btc", amount }]
  );
}

async function withdraw(
  client: SigningCosmWasmClient,
  sender: string,
  receiptAmount: string
) {
  return client.execute(
    sender,
    GHOST_VAULT_BTC,
    { withdraw: {} },
    "auto",
    "",
    [{ denom: "x/ghost-vault/btc", amount: receiptAmount }]
  );
}

async function getPosition(
  client: SigningCosmWasmClient,
  userAddress: string
) {
  const balance = await client.getBalance(userAddress, "x/ghost-vault/btc");
  const status = await client.queryContractSmart(GHOST_VAULT_BTC, { status: {} });

  const underlying = BigInt(balance.amount) *
    BigInt(status.deposit_pool.size) /
    BigInt(status.deposit_pool.shares);

  return {
    receiptTokens: balance.amount,
    underlyingValue: underlying.toString(),
    currentApy: status.lend_rate
  };
}
```

#### Complete Borrowing Flow (TypeScript)

```typescript
const GHOST_CREDIT = "<GHOST_CREDIT_ADDRESS>";

async function createCreditAccount(
  client: SigningCosmWasmClient,
  sender: string,
  tag: string
) {
  const salt = Buffer.from(Date.now().toString()).toString("base64");

  const result = await client.execute(
    sender,
    GHOST_CREDIT,
    {
      create: {
        salt,
        label: `Credit Account ${tag}`,
        tag
      }
    },
    "auto"
  );

  // Parse account address from events
  const event = result.events.find(e =>
    e.type === "wasm-rujira-ghost-credit/create_account"
  );
  return event?.attributes.find(a => a.key === "account")?.value;
}

async function openLoan(
  client: SigningCosmWasmClient,
  sender: string,
  creditAccount: string,
  collateralDenom: string,
  collateralAmount: string,
  borrowDenom: string,
  borrowAmount: string
) {
  // Step 1: Send collateral to credit account
  await client.sendTokens(
    sender,
    creditAccount,
    [{ denom: collateralDenom, amount: collateralAmount }],
    "auto"
  );

  // Step 2: Borrow against collateral
  return client.execute(
    sender,
    GHOST_CREDIT,
    {
      account: {
        addr: creditAccount,
        msgs: [
          { borrow: { denom: borrowDenom, amount: borrowAmount } }
        ]
      }
    },
    "auto"
  );
}

async function repayAndClose(
  client: SigningCosmWasmClient,
  sender: string,
  creditAccount: string,
  debtDenom: string,
  debtAmount: string,
  collateralDenom: string,
  collateralAmount: string
) {
  // Step 1: Send repayment tokens to credit account
  await client.sendTokens(
    sender,
    creditAccount,
    [{ denom: debtDenom, amount: debtAmount }],
    "auto"
  );

  // Step 2: Repay and withdraw
  return client.execute(
    sender,
    GHOST_CREDIT,
    {
      account: {
        addr: creditAccount,
        msgs: [
          { repay: { denom: debtDenom, amount: debtAmount } },
          { send: { to_address: sender, funds: [{ denom: collateralDenom, amount: collateralAmount }] } }
        ]
      }
    },
    "auto"
  );
}
```

***

### Appendix A: Message Reference

#### Ghost Vault Execute Messages

```json
// Deposit
{ "deposit": {} }
// Attach funds: [{ "denom": "btc", "amount": "100000000" }]

// Withdraw
{ "withdraw": {} }
// Attach funds: [{ "denom": "x/ghost-vault/btc", "amount": "100000000" }]
```

#### Ghost Vault Query Messages

```json
// Get config
{ "config": {} }

// Get status (rates, utilization)
{ "status": {} }
```

#### Ghost Credit Execute Messages

```json
// Create account
{
  "create": {
    "salt": "base64-encoded-salt",
    "label": "My Account",
    "tag": "optional-tag"
  }
}

// Account operations (batched)
{
  "account": {
    "addr": "thor1...",
    "msgs": [
      { "borrow": { "denom": "usdc", "amount": "1000000000" } },
      { "repay": { "denom": "usdc", "amount": "500000000" } },
      { "send": { "to_address": "thor1...", "funds": [...] } },
      { "transfer": "thor1new_owner..." },
      { "set_preference_order": { "denom": "btc", "after": "eth" } },
      { "set_preference_msgs": [...] }
    ]
  }
}
```

#### Ghost Credit Query Messages

```json
// Get config
{ "config": {} }

// Get single account
{ "account": "thor1..." }

// Get accounts by owner
{ "accounts": { "owner": "thor1...", "tag": "optional" } }

// Get all accounts (paginated)
{ "all_accounts": { "cursor": "thor1...", "limit": 100 } }

// Predict account address
{ "predict": { "owner": "thor1...", "salt": "base64..." } }

// Get borrow capacity
{ "borrows": {} }
```

***

### Appendix B: Response Types

#### StatusResponse (Ghost Vault)

```typescript
interface StatusResponse {
  last_updated: string;      // Nanosecond timestamp
  utilization_ratio: string; // Decimal (0-1)
  debt_rate: string;         // Annual borrow rate
  lend_rate: string;         // Annual supply rate
  debt_pool: PoolResponse;
  deposit_pool: PoolResponse;
}

interface PoolResponse {
  size: string;    // Total underlying tokens
  shares: string;  // Total shares issued
  ratio: string;   // size/shares ratio
}
```

#### AccountResponse (Ghost Credit)

```typescript
interface AccountResponse {
  owner: string;
  account: string;
  tag: string;
  ltv: string;
  collaterals: CollateralResponse[];
  debts: DebtResponse[];
  liquidation_preferences: LiquidationPreferences;
}

interface CollateralResponse {
  collateral: { coin: { denom: string; amount: string } };
  value_full: string;     // USD value
  value_adjusted: string; // USD value * collateral_factor
}

interface DebtResponse {
  debt: {
    addr: string;
    borrower: { denom: string; current: string; /* ... */ };
    current: string;
    shares: string;
  };
  value: string;  // USD value
}
```


---

# 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-lend-and-borrow.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.
