# Suilend SDK API Reference

This document provides detailed API reference for all public methods and interfaces in the Suilend SDK.

## Table of Contents

* \[SuilendClient]
* \[Static Methods]
* \[Instance Methods]
* \[Types and Interfaces]
* \[Constants]
* \[Error Handling]

## SuilendClient

The main client class that provides all functionality for interacting with Suilend lending markets.

### Constructor

```typescript
constructor(lendingMarket: LendingMarket<string>, client: SuiClient)
```

**Note**: Use the static `initialize()` method instead of calling the constructor directly.

### Static Methods

#### initialize

```typescript
static async initialize(
  lendingMarketId: string,
  lendingMarketType: string,
  client: SuiClient,
  logPackageId?: boolean
): Promise<SuilendClient>
```

Initializes a new SuilendClient instance.

**Parameters:**

* `lendingMarketId` (string): The ID of the lending market to interact with
* `lendingMarketType` (string): The type signature of the lending market
* `client` (SuiClient): Initialized Sui client instance
* `logPackageId` (boolean, optional): Whether to log the package ID during initialization

**Returns:** Promise

**Example:**

```typescript
const client = await SuilendClient.initialize(
  LENDING_MARKET_ID,
  LENDING_MARKET_TYPE,
  suiClient,
  true
);
```

#### getFeeReceivers

```typescript
static async getFeeReceivers(
  client: SuiClient,
  lendingMarketId: string
): Promise<FeeReceivers<string>>
```

Retrieves fee receiver configuration for a lending market.

**Parameters:**

* `client` (SuiClient): Sui client instance
* `lendingMarketId` (string): ID of the lending market

**Returns:** Promise\<FeeReceivers>

#### createNewLendingMarket

```typescript
static createNewLendingMarket(
  registryId: string,
  lendingMarketType: string,
  transaction: Transaction
): TransactionResult
```

Creates a new lending market in the specified registry.

**Parameters:**

* `registryId` (string): ID of the lending market registry
* `lendingMarketType` (string): Type signature for the new market
* `transaction` (Transaction): Transaction to add the creation call to

**Returns:** TransactionResult

#### getObligationOwnerCaps

```typescript
static async getObligationOwnerCaps(
  ownerId: string,
  lendingMarketTypeArgs: string[],
  client: SuiClient
): Promise<ObligationOwnerCap<string>[]>
```

Retrieves all obligation owner capabilities for a given owner.

**Parameters:**

* `ownerId` (string): Address of the obligation owner
* `lendingMarketTypeArgs` (string\[]): Type arguments for the lending market
* `client` (SuiClient): Sui client instance

**Returns:** Promise\<ObligationOwnerCap\[]>

#### getObligation

```typescript
static async getObligation(
  obligationId: string,
  lendingMarketTypeArgs: string[],
  client: SuiClient
): Promise<Obligation<string>>
```

Retrieves obligation data by ID.

**Parameters:**

* `obligationId` (string): ID of the obligation
* `lendingMarketTypeArgs` (string\[]): Type arguments for the lending market
* `client` (SuiClient): Sui client instance

**Returns:** Promise\<Obligation>

#### getLendingMarketOwnerCapId

```typescript
static async getLendingMarketOwnerCapId(
  ownerId: string,
  lendingMarketTypeArgs: string[],
  client: SuiClient
): Promise<string | null>
```

Retrieves the lending market owner capability ID for a given owner.

**Parameters:**

* `ownerId` (string): Address of the potential market owner
* `lendingMarketTypeArgs` (string\[]): Type arguments for the lending market
* `client` (SuiClient): Sui client instance

**Returns:** Promise\<string | null>

### Instance Methods

#### Core Operations

**createObligation**

```typescript
createObligation(transaction: Transaction): TransactionResult
```

Creates a new obligation in the lending market.

**Parameters:**

* `transaction` (Transaction): Transaction to add the creation call to

**Returns:** TransactionResult representing the obligation owner capability

**Example:**

```typescript
const tx = new Transaction();
const obligationOwnerCap = client.createObligation(tx);
```

**depositLiquidityAndGetCTokens**

```typescript
async depositLiquidityAndGetCTokens(
  ownerId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<TransactionResult>
```

Deposits liquidity into a reserve and receives cTokens in return.

**Parameters:**

* `ownerId` (string): Address of the depositor
* `coinType` (string): Type of the coin being deposited
* `value` (string): Amount to deposit (in smallest denomination)
* `transaction` (Transaction): Transaction to add the deposit call to

**Returns:** Promise representing the minted cTokens

**Example:**

```typescript
const tx = new Transaction();
const ctokens = await client.depositLiquidityAndGetCTokens(
  userAddress,
  "0x2::sui::SUI",
  "1000000000", // 1 SUI
  tx
);
```

**depositIntoObligation**

```typescript
async depositIntoObligation(
  ownerId: string,
  coinType: string,
  value: string,
  transaction: Transaction,
  obligationOwnerCapId: string | TransactionResult
): Promise<void>
```

Deposits tokens into an obligation as collateral.

**Parameters:**

* `ownerId` (string): Address of the depositor
* `coinType` (string): Type of the coin being deposited
* `value` (string): Amount to deposit
* `transaction` (Transaction): Transaction to modify
* `obligationOwnerCapId` (string | TransactionResult): Obligation owner capability

**Example:**

```typescript
const tx = new Transaction();
await client.depositIntoObligation(
  userAddress,
  "0x2::sui::SUI",
  "5000000000", // 5 SUI
  tx,
  obligationOwnerCapId
);
```

**withdraw**

```typescript
async withdraw(
  obligationOwnerCapId: string,
  obligationId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<TransactionResult>
```

Withdraws collateral from an obligation.

**Parameters:**

* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `obligationId` (string): ID of the obligation
* `coinType` (string): Type of coin to withdraw
* `value` (string): Amount to withdraw
* `transaction` (Transaction): Transaction to modify

**Returns:** Promise representing the withdrawn cTokens

**withdrawAndSendToUser**

```typescript
async withdrawAndSendToUser(
  ownerId: string,
  obligationOwnerCapId: string,
  obligationId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<void>
```

Withdraws collateral and automatically sends underlying tokens to user.

**Parameters:**

* `ownerId` (string): Address to send withdrawn tokens to
* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `obligationId` (string): ID of the obligation
* `coinType` (string): Type of coin to withdraw
* `value` (string): Amount to withdraw
* `transaction` (Transaction): Transaction to modify

**borrow**

```typescript
async borrow(
  obligationOwnerCapId: string,
  obligationId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<TransactionResult>
```

Borrows tokens against collateral in an obligation.

**Parameters:**

* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `obligationId` (string): ID of the obligation
* `coinType` (string): Type of coin to borrow
* `value` (string): Amount to borrow
* `transaction` (Transaction): Transaction to modify

**Returns:** Promise representing the borrowed tokens

**borrowAndSendToUser**

```typescript
async borrowAndSendToUser(
  ownerId: string,
  obligationOwnerCapId: string,
  obligationId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<void>
```

Borrows tokens and automatically sends them to the user.

**Parameters:**

* `ownerId` (string): Address to send borrowed tokens to
* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `obligationId` (string): ID of the obligation
* `coinType` (string): Type of coin to borrow
* `value` (string): Amount to borrow
* `transaction` (Transaction): Transaction to modify

**repayIntoObligation**

```typescript
async repayIntoObligation(
  ownerId: string,
  obligationId: string,
  coinType: string,
  value: string,
  transaction: Transaction
): Promise<void>
```

Repays borrowed amount into an obligation.

**Parameters:**

* `ownerId` (string): Address of the repayer
* `obligationId` (string): ID of the obligation
* `coinType` (string): Type of coin being repaid
* `value` (string): Amount to repay
* `transaction` (Transaction): Transaction to modify

**liquidate**

```typescript
async liquidate(
  transaction: Transaction,
  obligation: Obligation<string>,
  repayCoinType: string,
  withdrawCoinType: string,
  repayCoinId: TransactionObjectInput
): Promise<TransactionResult>
```

Liquidates an unhealthy obligation.

**Parameters:**

* `transaction` (Transaction): Transaction to modify
* `obligation` (Obligation): The obligation to liquidate
* `repayCoinType` (string): Type of coin used for repayment
* `withdrawCoinType` (string): Type of collateral to receive
* `repayCoinId` (TransactionObjectInput): Coin object used for repayment

**Returns:** Promise representing the liquidation bonus

**liquidateAndRedeem**

```typescript
async liquidateAndRedeem(
  transaction: Transaction,
  obligation: Obligation<string>,
  repayCoinType: string,
  withdrawCoinType: string,
  repayCoinId: TransactionObjectInput
): Promise<void>
```

Liquidates an obligation and automatically redeems cTokens for underlying assets.

**Parameters:**

* `transaction` (Transaction): Transaction to modify
* `obligation` (Obligation): The obligation to liquidate
* `repayCoinType` (string): Type of coin used for repayment
* `withdrawCoinType` (string): Type of collateral to receive
* `repayCoinId` (TransactionObjectInput): Coin object used for repayment

#### Reward Operations

**claimRewards**

```typescript
claimRewards(
  ownerId: string,
  obligationOwnerCapId: string,
  rewards: ClaimRewardsReward[],
  transaction: Transaction
): {
  transaction: Transaction;
  mergedCoinsMap: Record<string, TransactionObjectArgument>;
}
```

Claims multiple rewards from liquidity mining programs.

**Parameters:**

* `ownerId` (string): Address of the reward claimer
* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `rewards` (ClaimRewardsReward\[]): Array of rewards to claim
* `transaction` (Transaction): Transaction to modify

**Returns:** Object containing the modified transaction and merged coins map

**claimRewardsAndSendToUser**

```typescript
claimRewardsAndSendToUser(
  ownerId: string,
  obligationOwnerCapId: string,
  rewards: ClaimRewardsReward[],
  transaction: Transaction
): void
```

Claims rewards and automatically sends them to the user.

**Parameters:**

* `ownerId` (string): Address to send rewards to
* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `rewards` (ClaimRewardsReward\[]): Array of rewards to claim
* `transaction` (Transaction): Transaction to modify

**claimRewardsAndDeposit**

```typescript
claimRewardsAndDeposit(
  ownerId: string,
  obligationOwnerCapId: string,
  rewards: ClaimRewardsReward[],
  transaction: Transaction
): void
```

Claims rewards and automatically deposits them back into the protocol.

**Parameters:**

* `ownerId` (string): Address of the user
* `obligationOwnerCapId` (string): ID of the obligation owner capability
* `rewards` (ClaimRewardsReward\[]): Array of rewards to claim
* `transaction` (Transaction): Transaction to modify

#### Administrative Operations

**createReserve**

```typescript
async createReserve(
  lendingMarketOwnerCapId: string,
  transaction: Transaction,
  pythPriceId: string,
  coinType: string,
  createReserveConfigArgs: CreateReserveConfigArgs
): Promise<void>
```

Creates a new reserve in the lending market.

**Parameters:**

* `lendingMarketOwnerCapId` (string): ID of the lending market owner capability
* `transaction` (Transaction): Transaction to modify
* `pythPriceId` (string): Pyth price feed ID for the asset
* `coinType` (string): Type of the coin for the reserve
* `createReserveConfigArgs` (CreateReserveConfigArgs): Configuration for the reserve

**addReward**

```typescript
async addReward(
  ownerId: string,
  lendingMarketOwnerCapId: string,
  reserveArrayIndex: bigint,
  isDepositReward: boolean,
  rewardCoinType: string,
  rewardValue: string,
  startTimeMs: bigint,
  endTimeMs: bigint,
  transaction: Transaction,
  mergeCoins: boolean = true
): Promise<void>
```

Adds a liquidity mining reward to a reserve.

**Parameters:**

* `ownerId` (string): Address of the reward provider
* `lendingMarketOwnerCapId` (string): ID of the lending market owner capability
* `reserveArrayIndex` (bigint): Index of the reserve in the market
* `isDepositReward` (boolean): Whether this is a deposit or borrow reward
* `rewardCoinType` (string): Type of coin being provided as reward
* `rewardValue` (string): Amount of reward tokens
* `startTimeMs` (bigint): Start time in milliseconds
* `endTimeMs` (bigint): End time in milliseconds
* `transaction` (Transaction): Transaction to modify
* `mergeCoins` (boolean): Whether to merge coins for gas optimization

**cancelReward**

```typescript
cancelReward(
  lendingMarketOwnerCapId: string,
  reserveArrayIndex: bigint,
  isDepositReward: boolean,
  rewardIndex: bigint,
  rewardCoinType: string,
  transaction: Transaction
): void
```

Cancels an active reward program.

**Parameters:**

* `lendingMarketOwnerCapId` (string): ID of the lending market owner capability
* `reserveArrayIndex` (bigint): Index of the reserve
* `isDepositReward` (boolean): Whether this is a deposit or borrow reward
* `rewardIndex` (bigint): Index of the reward to cancel
* `rewardCoinType` (string): Type of reward coin
* `transaction` (Transaction): Transaction to modify

**closeReward**

```typescript
closeReward(
  lendingMarketOwnerCapId: string,
  reserveArrayIndex: bigint,
  isDepositReward: boolean,
  rewardIndex: bigint,
  rewardCoinType: string,
  transaction: Transaction
): void
```

Closes a completed reward program and claims remaining tokens.

**Parameters:**

* `lendingMarketOwnerCapId` (string): ID of the lending market owner capability
* `reserveArrayIndex` (bigint): Index of the reserve
* `isDepositReward` (boolean): Whether this is a deposit or borrow reward
* `rewardIndex` (bigint): Index of the reward to close
* `rewardCoinType` (string): Type of reward coin
* `transaction` (Transaction): Transaction to modify

**updateReserveConfig**

```typescript
updateReserveConfig(
  lendingMarketOwnerCapId: string,
  transaction: Transaction,
  coinType: string,
  createReserveConfigArgs: CreateReserveConfigArgs
): void
```

Updates the configuration of an existing reserve.

**Parameters:**

* `lendingMarketOwnerCapId` (string): ID of the lending market owner capability
* `transaction` (Transaction): Transaction to modify
* `coinType` (string): Type of coin for the reserve to update
* `createReserveConfigArgs` (CreateReserveConfigArgs): New configuration

#### Utility Methods

**refreshAll**

```typescript
async refreshAll(
  transaction: Transaction,
  obligation: Obligation<string>,
  extraReserveArrayIndex?: bigint
): Promise<void>
```

Refreshes price feeds and obligation state before performing operations.

**Parameters:**

* `transaction` (Transaction): Transaction to modify
* `obligation` (Obligation): Obligation to refresh
* `extraReserveArrayIndex` (bigint, optional): Additional reserve to refresh

**findReserveArrayIndex**

```typescript
findReserveArrayIndex(coinType: string): bigint
```

Finds the array index of a reserve by coin type.

**Parameters:**

* `coinType` (string): Type of coin to find

**Returns:** bigint representing the reserve array index

**Throws:** Error if reserve is not found

**getObligation**

```typescript
async getObligation(obligationId: string): Promise<Obligation<string>>
```

Retrieves obligation data using the client's lending market configuration.

**Parameters:**

* `obligationId` (string): ID of the obligation

**Returns:** Promise\<Obligation>

## Types and Interfaces

### ClaimRewardsReward

```typescript
interface ClaimRewardsReward {
  reserveArrayIndex: bigint;
  rewardIndex: bigint;
  rewardCoinType: string;
  side: Side;
}
```

### CreateReserveConfigArgs

```typescript
interface CreateReserveConfigArgs {
  openLtvPct: number;
  closeLtvPct: number;
  maxCloseLtvPct: number;
  borrowWeightBps: number;
  depositLimitUsd: number;
  borrowLimitUsd: number;
  liquidationBonusBps: number;
  maxLiquidationBonusBps: number;
  badDebtLiquidationBonusBps: number;
  minBorrowLimitUsd: number;
  isolatedAsset: boolean;
  openAttributedBorrowLimitUsd: number;
  closeAttributedBorrowLimitUsd: number;
}
```

### Side

```typescript
enum Side {
  DEPOSIT = "deposit",
  BORROW = "borrow",
}
```

### UiLendingMarket

```typescript
interface UiLendingMarket {
  name: string;
  slug: string;
  id: string;
  type: string;
  ownerCapId: string;
  isHidden?: boolean;
}
```

## Constants

### Lending Markets

```typescript
export const LENDING_MARKETS: UiLendingMarket[];
export const LENDING_MARKET_ID: string;
export const LENDING_MARKET_TYPE: string;
export const LENDING_MARKET_REGISTRY_ID: string;
export const ADMIN_ADDRESS: string;
```

### Package Information

```typescript
export const PACKAGE_ID: string;
export const PUBLISHED_AT: string;
```

## Error Handling

The SDK methods can throw various types of errors:

### Common Error Types

1. **Network Errors**: Connection issues with Sui RPC
2. **Transaction Errors**: Invalid transaction parameters or execution failures
3. **Insufficient Funds**: Not enough tokens for the requested operation
4. **Invalid Obligations**: Obligation not found or access denied
5. **Liquidation Errors**: Obligation not eligible for liquidation
6. **Configuration Errors**: Invalid reserve or market configuration

### Error Handling Best Practices

```typescript
try {
  await client.depositIntoObligation(/* parameters */);
} catch (error) {
  if (error.message.includes("insufficient funds")) {
    // Handle insufficient funds
  } else if (error.message.includes("obligation not found")) {
    // Handle missing obligation
  } else {
    // Handle other errors
    console.error("Unexpected error:", error);
  }
}
```

## Rate Limiting

When making multiple API calls, be aware of potential rate limiting from:

* Sui RPC endpoints
* Pyth price feed services
* Internal protocol rate limiters

Implement appropriate retry logic and backoff strategies for production applications.
