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

# Getting Started

Welcome to the **Zyfai SDK** documentation! This TypeScript SDK provides a comprehensive solution for interacting with the Zyfai Yield Optimization Engine, enabling you to deposit into Safe smart wallets, manage DeFi positions, and optimize yield across multiple protocols.

## What is Zyfai SDK?

The Zyfai SDK is a powerful TypeScript library that simplifies interaction with Zyfai's yield optimization infrastructure.

### Two Ways to Earn Yield

The SDK offers two distinct approaches for earning yield:

| Feature | Smart Wallet (Safe) | Vault |
| - | - | - |
| **Type** | Personal subaccount | Shared pool |
| **Chains** | Base, Arbitrum, Ethereum Mainnet | Base only |
| **Assets** | [USDC, WETH, EURC, USDT, PYUSD, NVDAc](/docs/sdk/supported-assets) | USDC |
| **Control** | Full ownership | Shares-based |
| **Withdrawals** | Direct | Async (request → claim) |
| **Optimization** | Automated rebalancing | Pool-managed |
| **Use case** | Advanced yield optimization | Simple deposit & earn |

* **Smart Wallet**: On first deposit, a personal pre-deployed Safe (with session key) is assigned for automated yield optimization across Base, Arbitrum, and Mainnet
* **Vault**: Deposit into a shared vault on Base and receive shares representing your stake

### Features

The SDK provides:

* **Pre-deployed Smart Wallets**: First `sendDeposit` assigns an ERC-4337 / ERC-7579 Safe with a signed session key
* **Flexible Authentication**: Support for private keys and modern wallet providers with automatic SIWE authentication
* **Multi-Chain Support**: Base (8453), Arbitrum (42161), and Ethereum Mainnet (1)
* **Multi-Asset Support**: USDC, WETH, EURC, USDT, PYUSD, and NVDAc — chains, decimals, and minimums are on [Supported Assets](/docs/sdk/supported-assets)
* **Yield Optimization**: Access multiple DeFi protocols and strategies
* **Position Tracking**: Monitor and manage your DeFi positions across chains
* **Analytics & Earnings**: Track earnings, APY history, and portfolio performance
* **SDK Key Analytics**: Access wallet lists and TVL data without requiring wallet connection

<Tip>
  Want to see the SDK in action before diving into the code? Check out our **Official Demo Application**.

  🔗 Repo: [**github.com/ondefy/zyfai-sdk-demo**](https://github.com/ondefy/zyfai-sdk-demo) <br /> 🔗 Website: [**demo.zyf.ai**](https://sdk.demo.zyf.ai)

  This Vite + React demo integrated with [Reown AppKit](https://reown.com/appkit) showcases:

  * **Wallet Connection** (EOA via AppKit)
  * **Fund Management** (Deposit / Withdrawal). The first deposit onboards the Safe.
  * **Real-time Data Retrieval** (Positions & Earnings)
</Tip>

## Prerequisites

Before you begin, ensure your environment meets these requirements:

1. **Node.js**: Version 18.0.0 or higher
2. **API Key**: Obtain your SDK API key from the [Zyfai Dashboard](https://sma.zyf.ai). How to hold it, and when an origin must be whitelisted, is below.

## API key and CORS

The dashboard key is a **partner credential** (`X-API-Key` on every call). It is not a user session. Keep it on a server you control.

Demo snippets in these docs and in the SDK repo sometimes pass `process.env.ZYFAI_API_KEY` (or `NEXT_PUBLIC_ZYFAI_API_KEY`) straight into a React component. A bundler ships that value in the frontend, so the key is public. A native app binary can be unpacked the same way. Those snippets are for demos. For a production web app or a wallet, your backend holds the key and proxies calls to Zyfai. The user still signs SIWE on their device.

Someone who only has the key **cannot move funds**. Deposits, withdrawals, and deposit registration return 401 without that user's SIWE session, and an on-chain transfer still needs their signature. What the key alone allows:

* Data API calls, counted against your quota
* Listing the smart wallets created under the key, and their TVL (`getSdkAllowedWallets`, `getSdkKeyTVL`)
* Registering extra wallets onto the key (`addWalletToSdk`)

That is an attribution and quota problem, not a custody problem.

CORS is a browser check. It does not apply to a native app or to a server calling `api.zyf.ai` / `defiapi.zyf.ai`.

| How you call Zyfai | Origin to whitelist |
| - | - |
| Browser page calling the APIs directly | The page origin, for example `https://app.example.com`. Contact the Zyfai team. Without it the browser blocks the response. |
| iOS or Android app | Nothing. A native HTTP client does not send a browser `Origin`. |
| Your backend or proxy | Nothing. The proxy URL (for example `https://api.example.com/ethereum/zyfai`) is not an origin we see. |

If a web app calls your proxy, and the proxy calls Zyfai from the server, whitelist nothing on our side. CORS is between the browser and your proxy.

## Installation

Install the SDK along with `viem` as a peer dependency.

**Latest version:**

<a href="https://www.npmjs.com/package/@zyfai/sdk">
  <img src="https://img.shields.io/npm/v/@zyfai/sdk" alt="npm" />
</a>

<CodeGroup>
  ```bash npm theme={null}
  npm install @zyfai/sdk viem
  ```

  ```bash yarn theme={null}
  yarn add @zyfai/sdk viem
  ```

  ```bash pnpm theme={null}
  pnpm add @zyfai/sdk viem
  ```
</CodeGroup>

## Architecture

The SDK bridges your application with two core backend systems. Full URLs, Swagger UIs, and which SDK methods hit which backend: [API Reference Overview](/docs/sdk/api/overview#backend-apis-openapi).

| Backend | Swagger UI | API base | Purpose |
| :- | :- | :- | :- |
| **Execution** | [api.zyf.ai/api-docs](https://api.zyf.ai/api-docs) | `https://api.zyf.ai/api/v1` | Deposits, withdrawals, transactions, session management, deposit registration |
| **DeFi data** | [defiapi.zyf.ai/api-docs](https://defiapi.zyf.ai/api-docs/) | `https://defiapi.zyf.ai/api/v2` | Earnings, opportunities, APY history, analytics |

***

## Quick Start

Follow these steps to integrate Zyfai into your application.

### 1. Initialize the SDK

Create a new instance of the Zyfai SDK with your configuration:

```typescript theme={null}
import { ZyfaiSDK } from "@zyfai/sdk";

const sdk = new ZyfaiSDK({
  apiKey: "your-api-key",
  rpcUrls: {
    // Optional: Custom RPC URLs per chain
    8453: "https://base-mainnet.g.alchemy.com/v2/YOUR_API_KEY",
    42161: "https://arb-mainnet.g.alchemy.com/v2/YOUR_API_KEY",
    9745: "https://your-plasma-rpc-provider.com",
  },
});
```

### 2. Connect an Account

The SDK handles SIWE (Sign-In with Ethereum) authentication automatically.

#### Option A: Backend/Node.js (Private Key)

```typescript theme={null}
const privateKey = "0x...";
const chainId = 42161; // Arbitrum

await sdk.connectAccount(privateKey, chainId);
```

#### Option B: Browser/Frontend (Wallet Provider)

```typescript theme={null}
// Works with any EIP-1193 provider (wagmi, web3-react, etc.)
const provider = window.ethereum; 

await sdk.connectAccount(provider);
```

<Info>
  `connectAccount()` performs the full SIWE handshake. No additional authentication logic is required in your application.
</Info>

### 3. Fund Management (onboarding via deposit)

Zyfai uses Safe smart accounts to manage user funds. There is **no separate deploy or session-key step**.

<Warning>
  The first `sendDeposit` call associates the EOA with a **pre-deployed Smart Account** that already has a **signed session key**. The Safe is available immediately on **Base, Arbitrum, and Ethereum Mainnet**. This does not change how the user's EOA works. They remain the owner of a linked Smart Wallet with session permissions for automated rebalancing.
</Warning>

#### Deposit

Transfer tokens from the EOA to the Safe smart wallet:

```typescript theme={null}
const userAddress = "0xUser...";
const chainId = 42161;
const amount = "100000000"; // 100 USDC (6 decimals)

// asset is required; strategy is optional (first deposit only, default: "conservative")
const deposit = await sdk.sendDeposit(
  userAddress,
  chainId,
  amount,
  "USDC",
  "conservative"
);

// Wait explicitly until the deposit is investable.
await sdk.waitForDepositCredit(deposit.registration.id, chainId);

// After first deposit, inspect the assigned Safe
const walletInfo = await sdk.getSmartWalletAddress(userAddress, chainId);
console.log(`Safe Address: ${walletInfo.address} (Deployed: ${walletInfo.isDeployed})`);
```

**Strategy Options** (applied on first deposit):

* `"conservative"` (default): Optimized for low-risk, stable yield.
* `"aggressive"`: Optimized for higher yield with higher risk profile.
* `"yieldmaxxing"`: Adds async vaults. Required for NVDAc.

Supported assets, decimals, and minimums: [Supported Assets](/docs/sdk/supported-assets).

#### Withdrawal

Initiate a withdrawal from the Safe back to an EOA:

```typescript theme={null}
// Full withdrawal
await sdk.withdrawFunds(userAddress, chainId);

// Partial withdrawal
await sdk.withdrawFunds(userAddress, chainId, "50000000"); // 50 USDC
```

<Warning>
  Withdrawals are processed asynchronously and will always complete, but not instantly. Follow these guidelines:

  * **Do not call `withdrawFunds` again** for the same withdrawal. Save `result.lifecycle.id` and poll with [`waitForWithdrawSettlement`](/docs/sdk/api/wait-for-withdraw-settlement) and, when needed, [`waitForWithdrawComplete`](/docs/sdk/api/wait-for-withdraw-complete).
  * **Track withdrawal state in your UI** from the lifecycle id (or a local flag keyed by that id) until status is `completed` or you surface async cooldown with `estimatedClaimAt`.
  * **`getHistory`** remains useful for displaying past transactions; lifecycle polling is the supported way to know when the current withdraw finishes.

  ```typescript theme={null}
  const result = await sdk.withdrawFunds(userAddress, chainId);
  const withdrawalId = result.lifecycle?.id;
  if (withdrawalId) {
    const settled = await sdk.waitForWithdrawSettlement(withdrawalId, chainId);
    if (settled.status !== "completed") {
      await sdk.waitForWithdrawComplete(withdrawalId, chainId);
    }
  }
  ```
</Warning>

### 4. Monitor Performance

```typescript theme={null}
// Get current positions
const positions = await sdk.getPositions(userAddress, chainId);

// Get lifetime earnings
const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);
const earnings = await sdk.getOnchainEarnings(wallet.address);

// Get 30-day APY history
const apy = await sdk.getDailyApyHistory(wallet.address, "30D");
```

***

## Full Workflow Example

Here is a complete integration script:

```typescript theme={null}
import { ZyfaiSDK } from "@zyfai/sdk";

async function runWorkflow() {
  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });

  try {
    // 1. Setup
    await sdk.connectAccount(process.env.PRIVATE_KEY!, 42161);
    const user = "0x...";
    const chainId = 42161;

    // 2. Deposit (first call assigns pre-deployed Safe + session)
    const deposit = await sdk.sendDeposit(user, chainId, "1000000", "USDC", "conservative");
    await sdk.waitForDepositCredit(deposit.registration.id, chainId);
    console.log("Deposit initiated:", deposit.txHash);

    // 4. Cleanup
    await sdk.disconnectAccount();
  } catch (err) {
    console.error("Workflow failed:", err);
  }
}
```

## Advanced Configuration

### Environment Variables

Store sensitive credentials securely:

```bash theme={null}
# .env
ZYFAI_API_KEY=zy_...
PRIVATE_KEY=0x...

# Optional Custom RPCs
BASE_RPC_URL=https://...
ARBITRUM_RPC_URL=https://...
```

### Custom RPC Setup

```typescript theme={null}
const sdk = new ZyfaiSDK({
  apiKey: process.env.ZYFAI_API_KEY!,
  rpcUrls: {
    8453: process.env.BASE_RPC_URL,
    42161: process.env.ARBITRUM_RPC_URL,
  },
});
```

## Key Features Deep Dive

### Pre-deployed Wallets

On first deposit, the backend assigns a pre-deployed Safe (with signed session key) to the EOA. The same Safe is available immediately on Base, Arbitrum, and Ethereum Mainnet.

### Session Key Security

Session keys ship with the pre-deployed Safe. They cannot withdraw funds to arbitrary addresses; they are strictly limited to rebalancing assets within the Zyfai ecosystem.

### Comprehensive Analytics

* **Platform-wide**: TVL, volume, and active user metrics.
* **User-specific**: Historical APY (7D–180D), detailed earnings breakdown, and transaction logs.

## Target Audience

* **dApp Developers**: Build DeFi apps with abstraction and yield optimization.
* **DeFi Services**: Manage Safe wallets and positions at scale.
* **Wallet Providers**: Embed yield optimization directly into your wallet UI.

## Troubleshooting

* **"No account connected"**: Ensure `sdk.connectAccount()` is called and resolved before executing transactions.
* **"Unsupported chain"**: Verify the chain ID is supported (1, 8453, 42161).
* **CORS Errors**: Only a browser calling Zyfai directly needs its page origin whitelisted. Contact the Zyfai team with that origin. A native app or a server-side proxy does not. See [API key and CORS](#api-key-and-cors).

## Next Steps

Check out the [API Reference](/docs/sdk/api/overview) for a detailed list of all available methods.

## Support

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


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