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

# 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                 | 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 `depositFunds` 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, and EURC (EURC on Mainnet and Base)
* **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 — 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)
3. **CORS Whitelist**: Your application domain must be whitelisted on the Zyfai backend to allow API calls from the browser. Contact the Zyfai team with your domain (e.g. `https://app.yourproject.com`) to get it added. Without this, browser-side SDK calls will be blocked by CORS policy.

## Installation

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

**Latest version:** `0.2.50`

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

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

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

## Architecture

The SDK bridges your application with two core backend systems:

| System            | Purpose                                                 | API Version |
| :---------------- | :------------------------------------------------------ | :---------- |
| **Execution API** | Deposits, withdrawals, transactions, session management | `/api/v1`   |
| **Data API**      | Earnings, opportunities, APY history, analytics         | `/api/v2`   |

***

## 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 `depositFunds` 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.depositFunds(
  userAddress,
  chainId,
  amount,
  "USDC",
  "conservative"
);

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

Supported assets: `"USDC"`, `"WETH"`, `"EURC"` (EURC on Mainnet and Base only).

<Info>
  Minimums apply to total Safe balance after deposit. Smaller top-ups are allowed if the Safe already meets the threshold.

  | Chain            | USDC     | WETH       |
  | ---------------- | -------- | ---------- |
  | Base / Arbitrum  | \$5      | 0.001 WETH |
  | Ethereum Mainnet | \$10,000 | 5 WETH     |
</Info>

#### 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 to handle them correctly:

  * **Do not poll the withdrawal endpoint repeatedly.** Once a withdrawal is initiated, it will be processed. Polling adds unnecessary load and can lead to duplicate requests.
  * **Track withdrawal state locally.** Save a flag in your local state (e.g. `isPendingWithdrawal: true`) as soon as `withdrawFunds()` is called. Use this flag to reflect a "pending" status in your UI.
  * **Use `sdk.getHistory()`** to confirm when the transaction has landed on-chain. Poll this endpoint at a reasonable interval (e.g. every 15–30 seconds) and clear your local flag once the transaction appears.

  ```typescript theme={null}
  // After calling withdrawFunds, set a local flag
  localStorage.setItem("withdrawalPending", "true");

  // Poll getHistory until the withdrawal appears
  const history = await sdk.getHistory(userAddress, chainId);
  const completed = history.some(tx => tx.type === "withdrawal");

  if (completed) {
    localStorage.removeItem("withdrawalPending");
  }
  ```
</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.depositFunds(user, chainId, "1000000", "USDC", "conservative");
    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/14D/30D), 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**: In browsers, ensure your domain is whitelisted in the Zyfai Dashboard.

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