> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zyf.ai/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.

## Backend APIs (OpenAPI)

`@zyfai/sdk` is a thin client over **two** production backends. Use the pages below for narrative method docs (parameters, examples). Use the OpenAPI (Swagger) UIs when you call the backends directly or debug SDK traffic.

| Backend | Swagger UI | API base | What the SDK uses it for |
| :- | :- | :- | :- |
| **Execution** | [api.zyf.ai/api-docs](https://api.zyf.ai/api-docs) | `https://api.zyf.ai/api/v1` | SIWE auth, user profile, Safe assignment, **`log_deposit` / v2**, deposit status, withdraws, session-related execution routes |
| **DeFi data** | [defiapi.zyf.ai/api-docs](https://defiapi.zyf.ai/api-docs/) | `https://defiapi.zyf.ai/api/v2` | APY, opportunities, earnings, analytics, token prices, and other [Intelligence Layer](/docs/sdk/intelligence-layer) reads |

Deposit registration and custody lifecycle (for example `log_deposit`, JWT, `credited` status) live on the **execution** API. Portfolio and yield **display** often pull from the **DeFi data** API after a deposit is **`credited`**.

Execution OpenAPI JSON: [api.zyf.ai/api-docs-json](https://api.zyf.ai/api-docs-json).

## 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 [`sendDeposit`](/docs/sdk/api/send-deposit) 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 |
| [setAssetStrategy](/docs/sdk/api/set-asset-strategy) | Switch one asset to a strategy and select its protocols |

### 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 |
| :- | :- |
| [sendDeposit](/docs/sdk/api/send-deposit) | Send, confirm, and register a deposit; await credit separately |
| [waitForDepositCredit](/docs/sdk/api/wait-for-deposit-credit) | Await deposit credit after `handover_pending` |
| [getDepositStatus](/docs/sdk/api/get-deposit-status) | Fetch deposit custody handover and credit lifecycle state |

For the normal user journey, call `sendDeposit`, then `waitForDepositCredit`
when the UI needs investable funds. Use `getDepositStatus` for refreshes rather
than holding a request open.

### External deposit composition

| Method | Description |
| :- | :- |
| [External deposit building blocks](/docs/sdk/api/external-deposit-building-blocks) | Configure, build, submit, and track an externally-sent deposit |
| [logDeposit](/docs/sdk/api/log-deposit) | Register a confirmed external deposit into the user's profile |

### Compatibility

| Method | Description |
| :- | :- |
| [depositFunds](/docs/sdk/api/deposit-funds) | Legacy convenience wrapper around send + short credit wait |

### Withdrawals

| Method | Description |
| :- | :- |
| [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 |
| [getAsyncOpportunities](/docs/sdk/api/get-async-opportunities) | Get yieldmaxxing opportunities, including pools with delayed withdrawals |
| [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 {
  const sent = await sdk.sendDeposit(userAddress, chainId, amount, "USDC");
  await sdk.waitForDepositCredit(sent.registration.id, chainId);
} 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

const sent = await sdk.sendDeposit(userAddress, chainId, amount, "USDC");
await sdk.waitForDepositCredit(sent.registration.id, chainId);
```

### 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)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.