npm package: @silo-finance/adapter-viem
Description: Viem adapter for Silo Finance SDK
Latest version: 0.0.1

# @silo-finance/adapter-viem

<a href="https://www.npmjs.com/package/@silo-finance/adapter-viem">
    <picture>
        <source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/@silo-finance/adapter-viem?colorA=21262d&colorB=21262d&style=flat">
        <img src="https://img.shields.io/npm/v/@silo-finance/adapter-viem?colorA=f6f8fa&colorB=f6f8fa&style=flat" alt="Version">
    </picture>
</a>
<a href="https://github.com/silo-finance/silo-sdk/blob/main/LICENSE">
    <picture>
        <source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/l/@silo-finance/adapter-viem?colorA=21262d&colorB=21262d&style=flat">
        <img src="https://img.shields.io/npm/l/@silo-finance/adapter-viem?colorA=f6f8fa&colorB=f6f8fa&style=flat" alt="MIT License">
    </picture>
</a>
<br />
<br />

Viem adapter for Silo Finance SDK. Provides `ViemAdapter` to connect the SDK to viem clients.

> **Note**: The `SiloSdk` class and modules are in [`@silo-finance/core`](../core/). This package provides the viem-specific adapter implementation.
>
> **Tip**: For bulk queries, historical data, or dashboards, consider also using [`@silo-finance/indexer`](../indexer/) for GraphQL access to indexed data.

## Installation

```bash
npm install @silo-finance/adapter-viem viem
```

```bash
pnpm add @silo-finance/adapter-viem viem
```

## Quick Start

### Using SiloSdk (Recommended)

```typescript
import { createPublicClient, http } from "viem";
import { arbitrum } from "viem/chains";
import { SiloSdk } from "@silo-finance/core";
import { ViemAdapter } from "@silo-finance/adapter-viem";

// 1. Create viem client
const publicClient = createPublicClient({ chain: arbitrum, transport: http() });

// 2. Create adapter
const adapter = new ViemAdapter({ provider: publicClient });

// 3. Create SDK instance
const sdk = new SiloSdk({ chain: "arbitrum", adapter });

// 4. Use namespaced API
const siloAddress = "0x...";
const borrowApr = await sdk.markets.getBorrowAPR(siloAddress);
const depositApr = await sdk.markets.getDepositAPR(siloAddress);
```

## SiloSdk Modules

| Module | Description |
|--------|-------------|
| `sdk.markets` | Fetch market data, APRs, utilization |
| `sdk.positions` | Fetch user positions, LTV, solvency |
| `sdk.actions` | Execute transactions (deposit, withdraw, borrow, repay) |
| `sdk.tokens` | Token balances, allowances, metadata |
| `sdk.calc` | Pure calculations (APY, risk level, etc.) |

## SDK Module Methods

### sdk.markets - Market Data

```typescript
// Fetch complete market structure
const market = await sdk.markets.get(siloConfigAddress);

// Fetch silo state
const silo = await sdk.markets.getSilo(siloAddress);

// Fetch raw silo storage data
const rawData = await sdk.markets.getRawSiloData(siloAddress);

// Fetch market config
const config = await sdk.markets.getConfig(configAddress, siloAddress);

// Fetch APRs
const borrowApr = await sdk.markets.getBorrowAPR(siloAddress);
const depositApr = await sdk.markets.getDepositAPR(siloAddress);
const utilization = await sdk.markets.getUtilization(siloAddress);
const liquidity = await sdk.markets.getLiquidity(siloAddress);

// Fetch all APRs in one bundled call
const aprs = await sdk.markets.getAPRs(siloAddress);
// Returns: { borrowApr, depositApr, utilization }
```

### sdk.positions - User Positions

```typescript
// Fetch full position for a user
const position = await sdk.positions.get(market, userAddress);
// Returns: { user, market, collaterals: [...], debts: [...] }

// Fetch collateral and debt balances
const balances = await sdk.positions.getBalances(siloAddress, userAddress);
// Returns: { collateral: bigint, debt: bigint }

// Check user LTV
const ltv = await sdk.positions.getLtv(siloAddress, userAddress);

// Check solvency
const isSolvent = await sdk.positions.isSolvent(siloAddress, userAddress);

// Check if user has any position
const hasPosition = await sdk.positions.hasPosition(siloConfigAddress, userAddress);

// Get all position data in one bundled call
const data = await sdk.positions.getData(siloAddress, userAddress);
// Returns: { ltv, collateralBalance, debtBalance, isSolvent }
```

### sdk.tokens - Token Data

```typescript
// Get token metadata
const metadata = await sdk.tokens.getMetadata(tokenAddress);
// Returns: { name: string, symbol: string, decimals: number }

// Get user balance
const balance = await sdk.tokens.getBalance(tokenAddress, userAddress);

// Get multiple balances in one call
const balances = await sdk.tokens.getBalances(tokenAddresses, userAddress);
// Returns: Map<Address, bigint>

// Get spending allowance
const allowance = await sdk.tokens.getAllowance(tokenAddress, ownerAddress, spenderAddress);
```

### Standalone Utility Functions

Oracle and router utilities are available as standalone functions:

```typescript
import {
  fetchQuote,
  fetchOracleQuotes,
  fetchQuoteToken,
  fetchRouterPaused,
} from "@silo-finance/adapter-viem";

// Get price quote for token
const quote = await fetchQuote(adapter, oracleAddress, tokenAddress, tokenDecimals);

// Get both lending and solvency quotes
const quotes = await fetchOracleQuotes(
  adapter,
  tokenAddress,
  tokenDecimals,
  lendingOracleAddress,
  solvencyOracleAddress
);
// Returns: { lendingQuote, solvencyQuote }

// Check if router is paused
const isPaused = await fetchRouterPaused(adapter, routerAddress);
```

### sdk.actions - Transactions

```typescript
// Approve tokens
await sdk.actions.approve({ token: tokenAddress, spender: siloAddress, amount });
await sdk.actions.approveMax({ token: tokenAddress, spender: siloAddress });

// Deposit collateral
const { hash } = await sdk.actions.deposit({
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
});

// Withdraw
const { hash } = await sdk.actions.withdraw({
  silo: siloAddress,
  assets: 500000n,
  receiver: userAddress,
  owner: userAddress,
});

// Borrow
const { hash } = await sdk.actions.borrow({
  silo: siloAddress,
  assets: 100000n,
  receiver: userAddress,
  borrower: userAddress,
});

// Repay
const { hash } = await sdk.actions.repay({
  silo: siloAddress,
  assets: 100000n,
  borrower: userAddress,
});
```

## Standalone Write Functions

All write functions return `{ hash: Hash }` and support gas overrides.

### Deposit & Withdraw

```typescript
import {
  deposit,
  depositProtected,
  withdraw,
  withdrawProtected,
} from "@silo-finance/adapter-viem";

// Deposit collateral
const { hash } = await deposit(walletClient, {
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
});

// Deposit as protected collateral (can't be borrowed against)
const { hash } = await depositProtected(walletClient, {
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
});

// Withdraw
const { hash } = await withdraw(walletClient, {
  silo: siloAddress,
  assets: 500000n,
  receiver: userAddress,
  owner: userAddress,
});
```

### Borrow & Repay

```typescript
import {
  borrow,
  borrowShares,
  repay,
  repayAssets,
} from "@silo-finance/adapter-viem";

// Borrow assets
const { hash } = await borrow(walletClient, {
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
  borrower: userAddress,
});

// Borrow by specifying shares to mint
const { hash } = await borrowShares(walletClient, {
  silo: siloAddress,
  shares: 1000000n,
  receiver: userAddress,
  borrower: userAddress,
});

// Repay by shares
const { hash } = await repay(walletClient, {
  silo: siloAddress,
  shares: 1000000n,
  borrower: userAddress,
});

// Repay by assets
const { hash } = await repayAssets(walletClient, {
  silo: siloAddress,
  assets: 1000000n,
  borrower: userAddress,
});
```

### Collateral Management

```typescript
import { transitionCollateral } from "@silo-finance/adapter-viem";

// Transition between collateral types
const { hash } = await transitionCollateral(walletClient, {
  silo: siloAddress,
  shares: 1000000n,
  owner: userAddress,
  transitionFrom: SiloCollateralType.Collateral, // to Protected
});
```

### ERC20 Approvals

```typescript
import { approve, approveMax } from "@silo-finance/adapter-viem";

// Approve specific amount
const { hash } = await approve(walletClient, {
  token: tokenAddress,
  spender: siloAddress,
  amount: 1000000n,
});

// Approve max (infinite)
const { hash } = await approveMax(walletClient, {
  token: tokenAddress,
  spender: siloAddress,
});
```

## Transaction Builders

Build transaction data without sending, useful for simulations or batching:

```typescript
import {
  buildDepositTx,
  buildWithdrawTx,
  buildBorrowTx,
  buildRepayTx,
  buildApproveTx,
} from "@silo-finance/adapter-viem";

// Get transaction config for viem
const tx = buildDepositTx({
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
});

// Use with simulateContract or multicall
const result = await client.simulateContract(tx);
```

## Gas Overrides

All write functions accept optional gas parameters:

```typescript
const { hash } = await deposit(walletClient, {
  silo: siloAddress,
  assets: 1000000n,
  receiver: userAddress,
  gas: 500000n,
  maxFeePerGas: parseGwei("50"),
  maxPriorityFeePerGas: parseGwei("2"),
});
```

## Client Types

```typescript
import type { ReadClient, WriteClient } from "@silo-finance/adapter-viem";

// ReadClient = PublicClient (viem)
// WriteClient = WalletClient (viem)
```

## License

[MIT](/LICENSE)