zyfai-sdkEarn yield on any Ethereum wallet on Base, Arbitrum, and Plasma. Use when a user wants passive DeFi yield on their funds. Deploys a non-custodial determinist...
Install via ClawdBot CLI:
clawdbot install PaulDeFi/zyfai-sdkTurn any Ethereum wallet into a yield-generating account.
When a user wants to earn yield on their crypto, Zyfai creates a subaccount (Safe smart wallet) linked to their existing wallet (EOA). Funds deposited into this subaccount are automatically optimized across DeFi protocols. The user stays in full control and can withdraw anytime.
βββββββββββββββββββ ββββββββββββββββββββββββ
β User's EOA β ββββΊ β Zyfai Subaccount β
β (their wallet) β β (Safe smart wallet) β
β β β β
β Owns & controlsβ β β’ Auto-rebalancing β
β β β β’ Yield optimizationβ
β β β β’ Non-custodial β
βββββββββββββββββββ ββββββββββββββββββββββββ
Key points:
1. DEPLOY β Create subaccount linked to user's wallet
2. SESSION β Enable automated yield optimization
3. DEPOSIT β Send funds to subaccount (starts earning)
4. WITHDRAW β Pull funds back to wallet (anytime)
npm install @zyfai/sdk viem
| Chain | ID |
|----------|-------|
| Arbitrum | 42161 |
| Base | 8453 |
| Plasma | 9745 |
When calling SDK methods, always pass the EOA address (the user's wallet address) as userAddress β never the subaccount/Safe address. The SDK derives the subaccount address automatically from the EOA.
import { ZyfaiSDK } from "@zyfai/sdk";
const sdk = new ZyfaiSDK({ apiKey: "your-api-key" });
// Use the private key provided by the agent
await sdk.connectAccount(privateKey, 8453); // chainId
Important: Always use the private key that the agent has access to. The private key must correspond to the EOA you're operating on.
const userAddress = "0x..."; // User's EOA (NOT the subaccount address!)
const chainId = 8453; // Base
// Check if subaccount exists
const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);
console.log(`Subaccount: ${wallet.address}`);
console.log(`Deployed: ${wallet.isDeployed}`);
// Deploy if needed
if (!wallet.isDeployed) {
const result = await sdk.deploySafe(userAddress, chainId, "conservative");
console.log("Subaccount deployed:", result.safeAddress);
}
Strategies:
"conservative" β Stable yield, lower risk"aggressive" β Higher yield, higher riskawait sdk.createSessionKey(userAddress, chainId);
// Always verify the session key was activated
const user = await sdk.getUserDetails();
if (!user.user.hasActiveSessionKey) {
// Session key not active β retry the process
console.log("Session key not active, retrying...");
await sdk.createSessionKey(userAddress, chainId);
// Verify again
const userRetry = await sdk.getUserDetails();
if (!userRetry.user.hasActiveSessionKey) {
throw new Error("Session key activation failed after retry. Contact support.");
}
}
console.log("Session key active:", user.user.hasActiveSessionKey);
This allows Zyfai to rebalance funds automatically. Session keys cannot withdraw to arbitrary addresses β only optimize within the protocol.
Important: Always verify the session key is active by checkinggetUserDetails().user.hasActiveSessionKeyafter callingcreateSessionKey. If it returnsfalse, retry the process. A session key must be active for automated yield optimization to work.
// Deposit 10 USDC (6 decimals)
await sdk.depositFunds(userAddress, chainId, "10000000");
Funds move from EOA β Subaccount and start earning yield immediately.
// Withdraw everything
await sdk.withdrawFunds(userAddress, chainId);
// Or withdraw partial (5 USDC)
await sdk.withdrawFunds(userAddress, chainId, "5000000");
Funds return to the user's EOA. Withdrawals are processed asynchronously.
await sdk.disconnectAccount();
import { ZyfaiSDK } from "@zyfai/sdk";
async function startEarningYield(userAddress: string, privateKey: string) {
const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
const chainId = 8453; // Base
// Connect using the agent's private key
await sdk.connectAccount(privateKey, chainId);
// Deploy subaccount if needed (always pass EOA as userAddress)
const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);
if (!wallet.isDeployed) {
await sdk.deploySafe(userAddress, chainId, "conservative");
console.log("Subaccount created:", wallet.address);
}
// Enable automated optimization
await sdk.createSessionKey(userAddress, chainId);
// Verify session key is active
const user = await sdk.getUserDetails();
if (!user.user.hasActiveSessionKey) {
console.log("Session key not active, retrying...");
await sdk.createSessionKey(userAddress, chainId);
const userRetry = await sdk.getUserDetails();
if (!userRetry.user.hasActiveSessionKey) {
throw new Error("Session key activation failed. Contact support.");
}
}
// Deposit 100 USDC
await sdk.depositFunds(userAddress, chainId, "100000000");
console.log("Deposited! Now earning yield.");
await sdk.disconnectAccount();
}
async function withdrawYield(userAddress: string, privateKey: string, amount?: string) {
const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });
const chainId = 8453; // Base
// Connect using the agent's private key
await sdk.connectAccount(privateKey, chainId);
// Withdraw funds (pass EOA as userAddress)
if (amount) {
// Partial withdrawal
await sdk.withdrawFunds(userAddress, chainId, amount);
console.log(`Withdrawn ${amount} (6 decimals) to EOA`);
} else {
// Full withdrawal
await sdk.withdrawFunds(userAddress, chainId);
console.log("Withdrawn all funds to EOA");
}
await sdk.disconnectAccount();
}
| Method | Params | Description |
|--------|--------|-------------|
| connectAccount | (privateKey, chainId) | Authenticate with Zyfai |
| getSmartWalletAddress | (userAddress, chainId) | Get subaccount address & status |
| deploySafe | (userAddress, chainId, strategy) | Create subaccount |
| createSessionKey | (userAddress, chainId) | Enable auto-optimization |
| depositFunds | (userAddress, chainId, amount) | Deposit USDC (6 decimals) |
| withdrawFunds | (userAddress, chainId, amount?) | Withdraw (all if no amount) |
| getPositions | (userAddress, chainId?) | Get active DeFi positions |
| getAvailableProtocols | (chainId) | Get available protocols & pools |
| getAPYPerStrategy | (crossChain?, days?, strategyType?) | Get APY for conservative/aggressive strategies |
| getUserDetails | () | Get authenticated user details |
| getOnchainEarnings | (walletAddress) | Get earnings data |
| updateUserProfile | (params) | Update strategy, protocols, splitting, cross-chain settings |
| registerAgentOnIdentityRegistry | (smartWallet, chainId) | Register agent on ERC-8004 Identity Registry |
| disconnectAccount | () | End session |
Note: All methods that take userAddress expect the EOA address, not the subaccount/Safe address.
Get all active DeFi positions for a user across protocols. Optionally filter by chain.
Parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| userAddress | string | β | User's EOA address |
| chainId | SupportedChainId | β | Optional: Filter by specific chain ID |
Example:
// Get all positions across all chains
const positions = await sdk.getPositions("0xUser...");
// Get positions on Arbitrum only
const arbPositions = await sdk.getPositions("0xUser...", 42161);
Returns:
interface PositionsResponse {
success: boolean;
userAddress: string;
positions: Position[];
}
Get available DeFi protocols and pools for a specific chain with APY data.
const protocols = await sdk.getAvailableProtocols(42161); // Arbitrum
protocols.protocols.forEach((protocol) => {
console.log(`${protocol.name} (ID: ${protocol.id})`);
if (protocol.pools) {
protocol.pools.forEach((pool) => {
console.log(` Pool: ${pool.name} - APY: ${pool.apy || "N/A"}%`);
});
}
});
Returns:
interface ProtocolsResponse {
success: boolean;
chainId: SupportedChainId;
protocols: Protocol[];
}
Get current authenticated user details including smart wallet, chains, protocols, and settings. Requires SIWE authentication.
await sdk.connectAccount(privateKey, chainId);
const user = await sdk.getUserDetails();
console.log("Smart Wallet:", user.user.smartWallet);
console.log("Chains:", user.user.chains);
console.log("Has Active Session:", user.user.hasActiveSessionKey);
Returns:
interface UserDetailsResponse {
success: boolean;
user: {
id: string;
address: string;
smartWallet?: string;
chains: number[];
protocols: Protocol[];
hasActiveSessionKey: boolean;
email?: string;
strategy?: string;
telegramId?: string;
walletType?: string;
autoSelectProtocols: boolean;
autocompounding?: boolean;
omniAccount?: boolean;
crosschainStrategy?: boolean;
agentName?: string;
customization?: Record<string, string[]>;
};
}
Update the authenticated user's profile settings including strategy, protocols, splitting, and cross-chain options. Requires SIWE authentication.
sdk.updateUserProfile(params: UpdateUserProfileRequest): Promise<UpdateUserProfileResponse>
Parameters:
interface UpdateUserProfileRequest {
/** Investment strategy: "conservative" for safer yields, "aggressive" for higher risk/reward */
strategy?: "conservative" | "aggressive";
/** Array of protocol IDs to use for yield optimization */
protocols?: string[];
/** Enable omni-account feature for cross-chain operations */
omniAccount?: boolean;
/** Enable automatic compounding of earned yields (default: true) */
autocompounding?: boolean;
/** Custom name for your agent */
agentName?: string;
/** Enable cross-chain strategy execution */
crosschainStrategy?: boolean;
/** Enable position splitting across multiple protocols */
splitting?: boolean;
/** Minimum number of splits when position splitting is enabled (1-4) */
minSplits?: number;
}
Returns:
interface UpdateUserProfileResponse {
success: boolean;
userId: string;
smartWallet?: string;
chains?: number[];
strategy?: string;
protocols?: string[];
omniAccount?: boolean;
autocompounding?: boolean;
agentName?: string;
crosschainStrategy?: boolean;
executorProxy?: boolean;
splitting?: boolean;
minSplits?: number;
}
Examples:
// Update strategy from conservative to aggressive
await sdk.updateUserProfile({
strategy: "aggressive",
});
// Configure specific protocols
const protocolsResponse = await sdk.getAvailableProtocols(8453);
const selectedProtocols = protocolsResponse.protocols
.filter(p => ["Aave", "Compound", "Moonwell"].includes(p.name))
.map(p => p.id);
await sdk.updateUserProfile({
protocols: selectedProtocols,
});
// Enable position splitting (distribute across multiple protocols)
await sdk.updateUserProfile({
splitting: true,
minSplits: 3, // Split across at least 3 protocols
});
// Verify changes
const userDetails = await sdk.getUserDetails();
console.log("Strategy:", userDetails.user.strategy);
console.log("Splitting:", userDetails.user.splitting);
Cross-chain strategies: Only enable cross-chain when the user explicitly requests it. For cross-chain to work, bothcrosschainStrategyandomniAccountmust be set totrue. Never enable cross-chain settings by default.
// Enable cross-chain ONLY when explicitly requested by the user
await sdk.updateUserProfile({
crosschainStrategy: true,
omniAccount: true,
});
// Now funds can be rebalanced across configured chains
const user = await sdk.getUserDetails();
console.log("Operating on chains:", user.user.chains);
Notes:
getAvailableProtocols(chainId) to get valid protocol IDs before updating.minSplits is set to 2, 3, or 4, funds are always distributed across at least that many pools for improved risk diversification (up to 4 DeFi pools). This guarantees your funds will be split regardless of market conditions.crosschainStrategy: true AND omniAccount: true. Only activate when the user explicitly asks for cross-chain yield optimization. Chains are configured during initial setup and cannot be changed via this method.true, yields are reinvested automatically.executorProxy cannot be updated via this method.Get global APY by strategy type (conservative or aggressive), time period, and chain configuration. Use this to compare expected returns between strategies before deploying.
Parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| crossChain | boolean | β | If true, returns APY for cross-chain strategies; if false, single-chain |
| days | number | β | Period over which APY is calculated. One of 7, 15, 30, 60 |
| strategyType | string | β | Strategy risk profile. One of 'conservative' or 'aggressive' |
Example:
// Get 7-day APY for conservative single-chain strategy
const conservativeApy = await sdk.getAPYPerStrategy(false, 7, 'conservative');
console.log("Conservative APY:", conservativeApy.data);
// Get 30-day APY for aggressive cross-chain strategy
const aggressiveApy = await sdk.getAPYPerStrategy(true, 30, 'aggressive');
console.log("Aggressive APY:", aggressiveApy.data);
// Compare strategies
const conservative = await sdk.getAPYPerStrategy(false, 30, 'conservative');
const aggressive = await sdk.getAPYPerStrategy(false, 30, 'aggressive');
console.log(`Conservative 30d APY: ${conservative.data[0]?.apy}%`);
console.log(`Aggressive 30d APY: ${aggressive.data[0]?.apy}%`);
Returns:
interface APYPerStrategyResponse {
success: boolean;
count: number;
data: APYPerStrategy[];
}
interface APYPerStrategy {
strategyType: string;
apy: number;
period: number;
crossChain: boolean;
}
Get onchain earnings for a wallet including total, current, and lifetime earnings.
const earnings = await sdk.getOnchainEarnings(smartWalletAddress);
console.log("Total earnings:", earnings.data.totalEarnings);
console.log("Current earnings:", earnings.data.currentEarnings);
console.log("Lifetime earnings:", earnings.data.lifetimeEarnings);
Returns:
interface OnchainEarningsResponse {
success: boolean;
data: {
walletAddress: string;
totalEarnings: number;
currentEarnings: number;
lifetimeEarnings: number;
unrealizedEarnings?: number;
currentEarningsByChain?: Record<string, number>;
unrealizedEarningsByChain?: Record<string, number>;
lastCheckTimestamp?: string;
};
}
Register your Zyfai deployed agent on the Identity Registry following the ERC-8004 standard. This is used for OpenClaw agent registration. The method fetches a tokenUri containing the agent's metadata stored on IPFS, then registers it on-chain.
Supported Chains:
| Chain | Chain ID |
|-------|----------|
| Base | 8453 |
| Arbitrum | 42161 |
Parameters:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| smartWallet | string | β | The Zyfai deployed smart wallet address to register as an agent |
| chainId | SupportedChainId | β | Chain ID (only 8453 or 42161) |
Example:
const sdk = new ZyfaiSDK({ apiKey: "your-api-key" });
await sdk.connectAccount(privateKey, 8453);
// Get smart wallet address
const walletInfo = await sdk.getSmartWalletAddress(userAddress, 8453);
const smartWallet = walletInfo.address;
// Register agent on Identity Registry
const result = await sdk.registerAgentOnIdentityRegistry(smartWallet, 8453);
console.log("Registration successful:");
console.log(" Tx Hash:", result.txHash);
console.log(" Chain ID:", result.chainId);
console.log(" Smart Wallet:", result.smartWallet);
Returns:
interface RegisterAgentResponse {
success: boolean;
txHash: string;
chainId: number;
smartWallet: string;
}
How It Works:
tokenUri from the Zyfai API (agent metadata stored on IPFS)register(tokenUri) call for the Identity Registry contractThe subaccount address should be identical across all chains for the same EOA. If you see different addresses:
// Check addresses on both chains
const baseWallet = await sdk.getSmartWalletAddress(userAddress, 8453);
const arbWallet = await sdk.getSmartWalletAddress(userAddress, 42161);
if (baseWallet.address !== arbWallet.address) {
console.error("Address mismatch! Contact support.");
}
If addresses don't match:
This means the wallet isn't registered in the backend. Solution:
deploySafe() first β even if the Safe is already deployed on-chain, this registers it with the backendcreateSessionKey()This typically means:
Verify you're using the correct private key for the EOA.
AI Usage Analysis
Analysis is being generated⦠refresh in a few seconds.
Connect Claude to Clawdbot instantly and keep it connected 24/7. Run after setup to link your subscription, then auto-refreshes tokens forever.
ERC-8004 Trustless Agents - Register, discover, and build reputation for AI agents on Ethereum. Use when registering agents on-chain, querying agent registries, giving/receiving reputation feedback, or interacting with the AI agent trust layer.
Autonomous crypto trading on Base via Bankr. Use for trading tokens, monitoring launches, executing strategies, or managing a trading portfolio. Triggers on "trade", "buy", "sell", "launch", "snipe", "profit", "PnL", "portfolio balance", or any crypto trading task on Base.
Deploy ERC20 tokens on Base using Clanker SDK. Create tokens with built-in Uniswap V4 liquidity pools. Supports Base mainnet and Sepolia testnet. Requires PRIVATE_KEY in config.
Query DeFi portfolio data across 50+ chains via Zapper's GraphQL API. Use when the user wants to check wallet balances, DeFi positions, NFT holdings, token prices, or transaction history. Supports Base, Ethereum, Polygon, Arbitrum, Optimism, and more. Requires ZAPPER_API_KEY.
Interact with Solana blockchain via Helius APIs. Create/manage wallets, check balances (SOL + tokens), send transactions, swap tokens via Jupiter, and monitor addresses. Use for any Solana blockchain operation, crypto wallet management, token transfers, DeFi swaps, or portfolio tracking.