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
Prerequisites
Before you begin, make sure you have:
- Node.js version 18.0.0 or higher
- API Key from the Zyfai Dashboard:
- Zyfai SDK API Key (required for transactions and Safe deployment)
Installation
Install the SDK and its peer dependency:
npm install @zyfai/sdk viem
# or
yarn add @zyfai/sdk viem
# or
pnpm add @zyfai/sdk viem
Architecture
The SDK connects to two separate backends:
| Backend | Purpose | API Version |
|---|---|---|
| Execution API | Safe deployment, transactions, session keys, withdrawals | /api/v1 |
| Data API | Earnings, opportunities, APY history, analytics | /api/v2 |
Quick Start
Step 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",
environment: "production", // or 'staging' (default: 'production')
rpcUrls: { // Optional: Custom RPC URLs per chain to avoid rate limiting
8453: "https://base-mainnet.g.alchemy.com/v2/YOUR_API_KEY", // Base
42161: "https://arb-mainnet.g.alchemy.com/v2/YOUR_API_KEY", // Arbitrum
9745: "https://your-plasma-rpc-provider.com", // Plasma
},
});
Step 2: Connect an Account
The SDK supports two ways to connect:
Option A: Using a Private Key (Backend/Node.js)
const privateKey = "0x...";
const chainId = 42161; // Arbitrum
// Automatically authenticates via SIWE
await sdk.connectAccount(privateKey, chainId);
Option B: Using a Wallet Provider (Browser/Frontend)
// Get provider from your wallet library (wagmi, web3-react, etc.)
const provider = window.ethereum; // or await connector.getProvider()
// Automatically authenticates via SIWE and detects chain from provider
await sdk.connectAccount(provider);
Note:
connectAccount()automatically performs SIWE (Sign-In with Ethereum) authentication. No additional steps needed!
Step 3: Deploy a Safe Wallet
Deploy a Safe smart wallet for a user:
const userAddress = "0xUser..."; // User's EOA address
const chainId = 42161; // Arbitrum
// Check if Safe already exists
const walletInfo = await sdk.getSmartWalletAddress(userAddress, chainId);
console.log("Safe Address:", walletInfo.address);
console.log("Is Deployed:", walletInfo.isDeployed);
// Deploy the Safe (automatically checks if already deployed)
if (!walletInfo.isDeployed) {
const result = await sdk.deploySafe(userAddress, chainId);
if (result.success) {
console.log("Safe deployed at:", result.safeAddress);
console.log("Transaction hash:", result.txHash);
}
}
Tip: The SDK automatically checks if a Safe is already deployed before attempting deployment.
Step 4: Create a Session Key
Create a session key for delegated transactions:
const result = await sdk.createSessionKey(userAddress, chainId);
if (result.alreadyActive) {
console.log("Session key already exists");
} else {
console.log("Session key created!");
console.log("Activation ID:", result.sessionActivation?.id);
}
Step 5: Deposit Funds
Transfer tokens to your Safe smart wallet:
const USDC_ARBITRUM = "0xaf88d065e77c8cc2239327c5edb3a432268e5831";
const amount = "100000000"; // 100 USDC (6 decimals: 100 * 10^6)
const depositResult = await sdk.depositFunds(
userAddress,
chainId,
USDC_ARBITRUM,
amount
);
if (depositResult.success) {
console.log("Deposit successful!");
console.log("Transaction Hash:", depositResult.txHash);
}
Important: Always use least decimal units for amounts. For USDC (6 decimals): 1 USDC = 1,000,000
Step 6: Monitor Positions and Earnings
Track your active DeFi positions and earnings:
// Get active positions
const positions = await sdk.getPositions(userAddress, chainId);
positions.positions.forEach((bundle) => {
console.log(`Chain: ${bundle.chain}, Strategy: ${bundle.strategy}`);
bundle.positions.forEach((slot) => {
console.log(` ${slot.token_symbol}: ${slot.underlyingAmount}`);
console.log(` Pool: ${slot.pool}, APY: ${slot.pool_apy}%`);
});
});
// Get earnings
const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);
const earnings = await sdk.getOnchainEarnings(wallet.address);
console.log("Total Earnings:", earnings.data.totalEarnings);
console.log("Current Earnings:", earnings.data.currentEarnings);
// Get APY history
const apy = await sdk.getDailyApyHistory(wallet.address, "30D");
console.log("30-Day Weighted APY:", apy.data.weightedAverageDailyAPY);
Step 7: Withdraw Funds
Initiate a withdrawal from your Safe:
// Full withdrawal
const withdrawResult = await sdk.withdrawFunds(userAddress, chainId);
// Partial withdrawal of 50 USDC
const partialWithdraw = await sdk.withdrawFunds(
userAddress,
chainId,
"50000000", // 50 USDC
"0xReceiverAddress" // Optional: custom receiver
);
if (withdrawResult.success) {
console.log("Withdrawal initiated:", withdrawResult.message);
}
Warning: Withdrawals are processed asynchronously by the backend. Use
getHistory()to track the withdrawal transaction once processed.
Step 8: Disconnect
When you're done, disconnect the account:
await sdk.disconnectAccount();
console.log("Account disconnected and authentication cleared");
Complete Example
Here's a complete workflow putting it all together:
import { ZyfaiSDK } from "@zyfai/sdk";
async function main() {
// 1. Initialize SDK
const sdk = new ZyfaiSDK({
apiKey: process.env.ZYFAI_API_KEY!,
environment: "production",
rpcUrls: {
// Optional: Custom RPC URLs to avoid rate limiting
8453: process.env.BASE_RPC_URL,
42161: process.env.ARBITRUM_RPC_URL,
9745: process.env.PLASMA_RPC_URL,
},
});
try {
// 2. Connect account
await sdk.connectAccount(process.env.PRIVATE_KEY!, 42161);
const userAddress = "0xUser...";
const chainId = 42161;
const USDC = "0xaf88d065e77c8cc2239327c5edb3a432268e5831";
// 3. Deploy Safe
const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);
if (!wallet.isDeployed) {
const deployResult = await sdk.deploySafe(userAddress, chainId);
console.log("Safe deployed:", deployResult.safeAddress);
}
// 4. Create session key
await sdk.createSessionKey(userAddress, chainId);
// 5. Deposit funds
const depositResult = await sdk.depositFunds(
userAddress,
chainId,
USDC,
"100000000"
);
console.log("Deposit tx:", depositResult.txHash);
// 6. Monitor positions
const positions = await sdk.getPositions(userAddress, chainId);
console.log("Active positions:", positions.positions.length);
// 7. Get earnings
const earnings = await sdk.getOnchainEarnings(wallet.address);
console.log("Total earnings:", earnings.data.totalEarnings);
// 8. Get available opportunities
const opportunities = await sdk.getSafeOpportunities(chainId);
console.log("Available pools:", opportunities.data.length);
// 9. Disconnect
await sdk.disconnectAccount();
} catch (error) {
console.error("Error:", error);
}
}
main();
Environment Variables
For production applications, store your API keys securely:
# .env file
ZYFAI_API_KEY=your-api-key
PRIVATE_KEY=0x... # For testing only - NEVER commit to version control
# Optional: Custom RPC URLs to avoid rate limiting
BASE_RPC_URL=https://base-mainnet.g.alchemy.com/v2/YOUR_API_KEY
ARBITRUM_RPC_URL=https://arb-mainnet.g.alchemy.com/v2/YOUR_API_KEY
PLASMA_RPC_URL=https://your-plasma-rpc-provider.com
Load them in your application:
import * as dotenv from "dotenv";
dotenv.config();
const sdk = new ZyfaiSDK({
apiKey: process.env.ZYFAI_API_KEY!,
rpcUrls: {
// Optional: Custom RPC URLs per chain to avoid rate limiting
8453: process.env.BASE_RPC_URL,
42161: process.env.ARBITRUM_RPC_URL,
9745: process.env.PLASMA_RPC_URL,
},
});
Key Features Deep Dive
Smart Wallet Management
Deploy and manage Safe smart wallets with deterministic addresses. The SDK handles all the complexity of Safe deployment, including ERC-4337 account abstraction and ERC-7579 module standards.
Session Keys
Create session keys with limited permissions for delegated transaction execution without exposing your main private key. Perfect for building secure dApps with enhanced UX.
Multi-Chain Support
Work seamlessly across multiple chains:
- Arbitrum (Chain ID: 42161)
- Base (Chain ID: 8453)
- Plasma (Chain ID: 9745)
Analytics & Data
Access comprehensive analytics including:
- Platform Metrics: Total Value Locked (TVL), trading volume, active wallets
- Earnings Tracking: Current, lifetime, and daily earnings with chain-level breakdowns
- APY Monitoring: Historical APY with weighted averages (7D, 14D, 30D)
- Position Tracking: Monitor active DeFi positions across all chains
- Transaction History: Complete transaction logs with pagination and filters
- Rebalance Analytics: Track rebalancing events and frequency tiers
- Portfolio Data: Multi-chain portfolio tracking (premium feature)
Yield Opportunities
Discover and access yield opportunities across multiple DeFi protocols:
- Safe Opportunities: Low-risk, stable yield strategies
- Degen Strategies: High-risk, high-reward opportunities
- Real-time APY Data: Up-to-date APY for all pools
- Protocol Information: Available protocols and pools by chain
Who Should Use This SDK?
dApp Developers
Build sophisticated DeFi applications with smart wallet integration, session keys, and yield optimization.
DeFi Services
Create backend services that manage Safe wallets and DeFi positions for multiple users.
Wallet Providers
Integrate Zyfai's yield optimization directly into your wallet application.
Financial Platforms
Build financial dashboards and analytics tools using Zyfai's data APIs.
Common Issues
"No account connected" Error
Make sure to call connectAccount() before calling other methods that require signing.
"Unsupported chain" Error
Verify you're using a supported chain ID:
- Arbitrum: 42161
- Base: 8453
- Plasma: 9745
SIWE Authentication Failures
In browser environments, ensure:
- Your frontend origin is allowed by the API's CORS configuration
- You're using the correct
environmentsetting - The user approves the SIWE signature request
Next Steps
Ready to explore the full API? Check out the complete API Reference with all 26 methods organized by category.
Support
Need help? Here are some resources:
- GitHub Issues: Report bugs or request features
- Documentation: Browse this comprehensive documentation
- Website: Visit zyf.ai for more information