Skip to main content

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 deploy 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. It provides:

  • Safe Smart Wallet Deployment: Deploy ERC-4337 and ERC-7579 compliant Safe smart accounts
  • Flexible Authentication: Support for private keys and modern wallet providers with automatic SIWE authentication
  • Multi-Chain Support: Works seamlessly on Arbitrum (42161), Base (8453), and Plasma (9745)
  • Session Key Management: Create and manage session keys for delegated transaction execution
  • 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
See it in Action

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

🔗 github.com/ondefy/zyfai-sdk-demo

This Vite + React demo integrated with Reown AppKit showcases:

  • Wallet Connection (EOA via AppKit)
  • Safe Deployment & Session Key management
  • Fund Management (Deposit/Withdrawal)
  • Real-time Data Retrieval (Positions & Earnings)

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

Installation

Install the SDK along with viem as a peer dependency:

npm install @zyfai/sdk viem

Architecture

The SDK bridges your application with two core backend systems:

SystemPurposeAPI Version
Execution APISafe deployment, transactions, session keys, withdrawals/api/v1
Data APIEarnings, 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:

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)

const privateKey = "0x...";
const chainId = 42161; // Arbitrum

await sdk.connectAccount(privateKey, chainId);

Option B: Browser/Frontend (Wallet Provider)

// Works with any EIP-1193 provider (wagmi, web3-react, etc.)
const provider = window.ethereum;

await sdk.connectAccount(provider);
Automatic SIWE

connectAccount() performs the full SIWE handshake. No additional authentication logic is required in your application.

3. Deploy a Safe Wallet

Zyfai uses Safe smart accounts to manage user funds securely.

const userAddress = "0xUser..."; 
const chainId = 42161;

// 1. Check current status
const walletInfo = await sdk.getSmartWalletAddress(userAddress, chainId);
console.log(`Safe Address: ${walletInfo.address} (Deployed: ${walletInfo.isDeployed})`);

// 2. Deploy if necessary
if (!walletInfo.isDeployed) {
const result = await sdk.deploySafe(userAddress, chainId, "conservative");

if (result.success) {
console.log("Safe deployed at:", result.safeAddress);
}
}

Strategy Options:

  • "conservative" (default): Optimized for low-risk, stable yield.
  • "aggressive": Optimized for higher yield with higher risk profile.

4. Manage Session Keys

Session keys allow the Zyfai engine to execute optimizations on behalf of the user within strict bounds.

const result = await sdk.createSessionKey(userAddress, chainId);

if (!result.alreadyActive) {
console.log("New session key registered:", result.sessionActivation?.id);
}

5. Fund Management

Deposit

Transfer tokens from the EOA to the Safe smart wallet:

const amount = "100000000"; // 100 USDC (6 decimals)

const deposit = await sdk.depositFunds(userAddress, chainId, amount);

Withdrawal

Initiate a withdrawal from the Safe back to an EOA:

// Full withdrawal
await sdk.withdrawFunds(userAddress, chainId);

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

Withdrawals are processed asynchronously. Use sdk.getHistory() to track the transaction status once it's on-chain.

6. Monitor Performance

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

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. Deployment & Keys
const wallet = await sdk.getSmartWalletAddress(user, chainId);
if (!wallet.isDeployed) await sdk.deploySafe(user, chainId);
await sdk.createSessionKey(user, chainId);

// 3. Execution
const deposit = await sdk.depositFunds(user, chainId, "1000000");
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:

# .env
ZYFAI_API_KEY=zy_...
PRIVATE_KEY=0x...

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

Custom RPC Setup

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

Deterministic Wallets

The SDK uses a deterministic deployment factory. This means a user's Safe address is calculated based on their EOA address, ensuring the same address across different chains.

Session Key Security

Session keys are created with specific permissions. 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 (42161, 8453, 9745).
  • CORS Errors: In browsers, ensure your domain is whitelisted in the Zyfai Dashboard.

Next Steps

Check out the API Reference for a detailed list of all available methods.

Support