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

# API Reference Overview

The Zyfai SDK provides a comprehensive TypeScript API for integrating DeFi yield optimization into your applications. All methods are fully typed and include built-in error handling.

## Quick Links

* [Getting Started](/docs/sdk/getting-started) - Full integration guide
* [Agent Quickstart](/docs/sdk/agent-quickstart) - Compact reference for AI agents

## API Organization

The SDK methods are organized into logical categories matching the sidebar navigation.

### Account Management

Manage wallet connections and SIWE authentication.

| Method                                                | Description                               |
| :---------------------------------------------------- | :---------------------------------------- |
| [connectAccount](/docs/sdk/api/connect-account)       | Connect wallet and authenticate with SIWE |
| [disconnectAccount](/docs/sdk/api/disconnect-account) | Disconnect and clear authentication state |

### Smart Wallet

Resolve and manage Safe smart wallets. The Safe (with session key) is assigned on the first [`depositFunds`](/docs/sdk/api/deposit-funds) call — there is no separate deploy or session-key API.

| Method                                                          | Description                          |
| :-------------------------------------------------------------- | :----------------------------------- |
| [getSmartWalletAddress](/docs/sdk/api/get-smart-wallet-address) | Get assigned Safe address for an EOA |
| [pauseAgent](/docs/sdk/api/pause-agent)                         | Pause automated yield optimization   |
| [resumeAgent](/docs/sdk/api/resume-agent)                       | Resume automated yield optimization  |

### Fund Management

Deposit and withdraw funds from your Smart Wallet. First deposit onboards the user onto a pre-deployed Safe with a signed session key (Base, Arbitrum, Mainnet).

| Method                                        | Description                                                 |
| :-------------------------------------------- | :---------------------------------------------------------- |
| [depositFunds](/docs/sdk/api/deposit-funds)   | Transfer tokens to Smart Wallet (onboards on first deposit) |
| [logDeposit](/docs/sdk/api/log-deposit)       | Log an external deposit into the user's profile             |
| [withdrawFunds](/docs/sdk/api/withdraw-funds) | Withdraw from active positions                              |

### User Data

Retrieve and update user profile, positions, and settings.

| Method                                                       | Description                                        |
| :----------------------------------------------------------- | :------------------------------------------------- |
| [getPositions](/docs/sdk/api/get-positions)                  | Get active positions and idle balances             |
| [getPortfolio](/docs/sdk/api/get-portfolio)                  | Get detailed portfolio with balances by asset type |
| [getUserDetails](/docs/sdk/api/get-user-details)             | Get current user profile and settings              |
| [updateUserProfile](/docs/sdk/api/update-user-details)       | Update strategy, protocols, splitting settings     |
| [getHistory](/docs/sdk/api/get-history)                      | Get transaction history                            |
| [customizeBatch](/docs/sdk/api/customize-batch)              | Configure protocol/pool preferences per chain      |
| [enableSplitting](/docs/sdk/api/enable-splitting)            | Enable position splitting across pools             |
| [disableSplitting](/docs/sdk/api/disable-splitting)          | Disable position splitting                         |
| [updateMinSplits](/docs/sdk/api/update-min-splits)           | Update minimum split count                         |
| [getFirstTopup](/docs/sdk/api/get-first-topup)               | Get first deposit information                      |
| [getSmartWalletByEOA](/docs/sdk/api/get-smart-wallet-by-eoa) | Map EOA to smart wallet address                    |

### Earnings & Performance

Track and calculate earnings and APY.

| Method                                                               | Description                              |
| :------------------------------------------------------------------- | :--------------------------------------- |
| [calculateOnchainEarnings](/docs/sdk/api/calculate-onchain-earnings) | Calculate earnings on-chain for a wallet |
| [getOnchainEarnings](/docs/sdk/api/get-onchain-earnings)             | Get current and lifetime earnings        |
| [getDailyApyHistory](/docs/sdk/api/get-daily-apy-history)            | Get APY history with weighted averages   |
| [getDailyEarnings](/docs/sdk/api/get-daily-earnings)                 | Get daily earnings breakdown             |

### Protocol Data

Access DeFi protocol information.

| Method                                                         | Description                                |
| :------------------------------------------------------------- | :----------------------------------------- |
| [getAvailableProtocols](/docs/sdk/api/get-available-protocols) | Get available protocols and pools by chain |

### Opportunities Data

Discover yield opportunities by risk profile.

| Method                                                                       | Description                              |
| :--------------------------------------------------------------------------- | :--------------------------------------- |
| [getAPYPerStrategy](/docs/sdk/api/get-apy-per-strategy)                      | Get APY by strategy type and period      |
| [getConservativeOpportunities](/docs/sdk/api/get-conservative-opportunities) | Get low-risk yield opportunities         |
| [getAggressiveOpportunities](/docs/sdk/api/get-aggressive-opportunities)     | Get high-risk, high-reward opportunities |
| [getActiveConservativeOppsRisk](/docs/sdk/api/getActiveConservativeOppsRisk) | Get risk data for conservative pools     |
| [getActiveAggressiveOppsRisk](/docs/sdk/api/getActiveAggressiveOppsRisk)     | Get risk data for aggressive pools       |
| [getConservativePoolStatus](/docs/sdk/api/getConservativePoolStatus)         | Get conservative pool status             |
| [getAggressivePoolStatus](/docs/sdk/api/getAggressivePoolStatus)             | Get aggressive pool status               |

### SDK Key Information

Get information about wallets and TVL for your SDK API key. **No wallet connection required.**

| Method                                                        | Description                                  |
| :------------------------------------------------------------ | :------------------------------------------- |
| [getSdkAllowedWallets](/docs/sdk/api/get-sdk-allowed-wallets) | Get list of wallets created via your SDK key |
| [getSdkKeyTVL](/docs/sdk/api/get-sdk-key-tvl)                 | Get total TVL across all SDK wallets         |

### Analytics & Metrics

Platform-wide analytics and metrics.

| Method                                               | Description                            |
| :--------------------------------------------------- | :------------------------------------- |
| [getTVL](/docs/sdk/api/get-tvl)                      | Get total value locked across platform |
| [getVolume](/docs/sdk/api/get-volume)                | Get total trading volume               |
| [getActiveWallets](/docs/sdk/api/get-active-wallets) | Get active wallets count by chain      |

### Rebalancing

Monitor rebalancing activity.

| Method                                                         | Description                      |
| :------------------------------------------------------------- | :------------------------------- |
| [getRebalanceFrequency](/docs/sdk/api/get-rebalance-frequency) | Get rebalance tier and frequency |

### ERC-8004

Agent identity registration on-chain.

| Method                                                                               | Description                                  |
| :----------------------------------------------------------------------------------- | :------------------------------------------- |
| [registerAgentOnIdentityRegistry](/docs/sdk/api/register-agent-on-identity-registry) | Register agent on ERC-8004 Identity Registry |

***

## Intelligence Layer

Read-only access to the Zyfai yield engine. **No wallet connection required** — API key only. See the [Intelligence Layer overview](/docs/sdk/intelligence-layer) for the full context.

### Yield Simulation

| Method                                                         | Description                                                                            |
| :------------------------------------------------------------- | :------------------------------------------------------------------------------------- |
| [simulateBestPositions](/docs/sdk/api/simulate-best-positions) | Preview the best yield split for an amount, with blended APY and ready-to-run calldata |

### Real-Time Risk Events

| Method                                                 | Description                                                                        |
| :----------------------------------------------------- | :--------------------------------------------------------------------------------- |
| [subscribeToEvents](/docs/sdk/api/subscribe-to-events) | Subscribe to live depegs, liquidity drops, and new collateral events via WebSocket |

***

## Common Patterns

### Authentication Required

Most methods require SIWE authentication, which is handled automatically when you call `connectAccount()`:

```typescript theme={null}
// Authentication is automatic
await sdk.connectAccount(privateKey, chainId);

// Now all protected methods work
const user = await sdk.getUserDetails();
```

### SDK Key Methods (No Wallet Required)

Some methods only require your SDK API key and don't need a wallet connection:

```typescript theme={null}
// Initialize SDK with just your API key
const sdk = new ZyfaiSDK({ apiKey: "zyfai_your_key" });

// No wallet connection needed
const wallets = await sdk.getSdkAllowedWallets();
const tvl = await sdk.getSdkKeyTVL();

console.log("Wallets created via SDK:", wallets.allowedWallets.length);
console.log("Total TVL:", tvl.totalTvl);
```

These methods are ideal for:

* B2B dashboards showing client metrics
* Analytics and monitoring without user interaction
* Server-side reporting and billing

### Chain IDs

The SDK supports three chains:

| Chain            | ID    |
| :--------------- | :---- |
| Base             | 8453  |
| Arbitrum         | 42161 |
| Ethereum Mainnet | 1     |

```typescript theme={null}
import { getSupportedChainIds, isSupportedChain } from "@zyfai/sdk";

const chains = getSupportedChainIds(); // [8453, 42161, 1]
const isValid = isSupportedChain(8453); // true
```

### Error Handling

All methods throw typed errors:

```typescript theme={null}
try {
  await sdk.depositFunds(userAddress, chainId, amount, "USDC");
} catch (error) {
  console.error("Deposit failed:", error.message);
}
```

### Amount Formatting

Token amounts are always in the **least decimal units** (wei):

```typescript theme={null}
// For USDC / EURC (6 decimals), 100 = 100 * 10^6
const amount = "100000000"; // 100 USDC

await sdk.depositFunds(userAddress, chainId, amount, "USDC");
```

### Async Processing

Some operations like withdrawals are processed asynchronously:

```typescript theme={null}
// Withdrawal is queued
const result = await sdk.withdrawFunds(userAddress, chainId);
console.log(result.message); // "Withdrawal request sent"

// Check history later to see completion
const history = await sdk.getHistory(walletAddress, chainId);
```

***

## Type Safety

The SDK is fully typed with TypeScript. Import types as needed:

```typescript theme={null}
import type {
  SDKConfig,
  DepositResponse,
  PositionsResponse,
  UpdateUserProfileResponse,
  SupportedChainId,
} from "@zyfai/sdk";
```

## Response Format

All SDK methods return consistent response objects:

```typescript theme={null}
{
  success: boolean; // Operation success status
  // ... method-specific data
}
```

## Rate Limiting

API calls are rate-limited. The SDK includes automatic retry logic with exponential backoff.

## Support

* [GitHub Issues](https://github.com/ondefy/zyfai-sdk/issues)
* [Telegram](https://t.me/zkzyfi)
* [Zyfai Website](https://zyf.ai)
