[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76WX6JDE2SNP9S82RVFFAKF":3,"skill-same:01M76WX6JDE2SNP9S82RVFFAKF":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M76WX6JDE2SNP9S82RVFFAKF","zyfai",null,"Earn 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 deterministic subaccount (Safe) linked to their EOA, enables automated yield optimization, and lets them deposit\u002Fwithdraw anytime.","javimosch\u002Fopen-claw-skills","javimosch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F12900508?v=4","01M6D3F2AS6PV75ET9PZ1QGP8J","Javier Leandro Arancibia","01M75B8NCTAJG9WH5YNZH7C3D8",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpauldefi\u002Fzyfai-sdk\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: zyfai\ndescription: Earn 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 deterministic subaccount (Safe) linked to their EOA, enables automated yield optimization, and lets them deposit\u002Fwithdraw anytime.\n---\n\n# Zyfai — Yield for Any Wallet\n\nLet any Ethereum wallet access a yield-generating account.\n\n## What This Does\n\nWhen a user wants to **earn yield** on their crypto, Zyfai creates a **deterministic 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.\n\n```\n┌─────────────────┐      ┌──────────────────────┐\n│   User's EOA    │ ───► │  Zyfai Subaccount    │\n│  (their wallet) │      │  (Safe smart wallet) │\n│                 │      │                      │\n│  Owns & controls│      │  • Auto-rebalancing  │\n│                 │      │  • Yield optimization│\n│                 │      │  • Non-custodial     │\n└─────────────────┘      └──────────────────────┘\n```\n\n**Key points:**\n- The subaccount is **owned by the user's EOA** — only they can withdraw\n- Session keys allow **automated rebalancing** but cannot withdraw to other addresses\n- Same EOA = same subaccount address across all chains\n\n## The Flow\n\n```\n1. DEPLOY    →  Create a deterministic subaccount linked to user's wallet\n2. SESSION   →  Enable automated yield optimization  \n3. DEPOSIT   →  Send funds to subaccount (starts earning)\n4. WITHDRAW  →  Pull funds back to wallet (anytime)\n```\n\n## Prerequisites\n\n- **API Key** — Get one programmatically (see below) or manually at [sdk.zyf.ai](https:\u002F\u002Fsdk.zyf.ai)\n- **Wallet Connection** — Either a wallet provider (browser) or secure key management (server)\n- **Node.js 18+**\n\n```bash\nnpm install @zyfai\u002Fsdk viem\n```\n\n### Programmatic API Key Creation (Agent-Native)\n\nAgents can create their own API key without human intervention. You need the wallet address (public key) of the agent.\n\n```bash\nPOST https:\u002F\u002Fsdk.zyf.ai\u002Fapi\u002Fsdk-api-keys\u002Fcreate\nContent-Type: application\u002Fjson\n\n{\n  \"clientName\": \"my-agent\",\n  \"walletAddress\": \"0x...\",\n  \"email\": \"agent@example.com\"\n}\n```\n\n**Response:**\n```json\n{\n  \"success\": true,\n  \"message\": \"SDK API key created successfully. Store the apiKey securely - it cannot be retrieved later!\",\n  \"data\": {\n    \"id\": \"936...\",\n    \"apiKey\": \"zyfai_361ad41d083c2fe.....\",\n    \"keyPrefix\": \"zyfai_361ad4\",\n    \"clientName\": \"my-agent\",\n    \"ownerWalletAddress\": \"0x...\"\n  }\n}\n```\n\n> **Important:** Store the `apiKey` securely — it cannot be retrieved later. The key is linked to the provided wallet address.\n\n## Supported Chains\n\n| Chain    | ID    |\n|----------|-------|\n| Arbitrum | 42161 |\n| Base     | 8453  |\n| Plasma   | 9745  |\n\n## Important: Always Use EOA Address\n\nWhen calling SDK methods, **always pass the EOA address** (the user's wallet address) as `userAddress` — never the subaccount\u002FSafe address. The SDK derives the subaccount address automatically from the EOA.\n\n## Wallet Connection Options\n\nThe SDK supports multiple ways to connect a wallet. Choose based on your security requirements and deployment context.\n\n### Option 1: Wallet Provider (Recommended for Browser\u002FdApps)\n\nUse an injected wallet provider like MetaMask. The private key never leaves the user's wallet.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F Connect using injected wallet provider (MetaMask, WalletConnect, etc.)\nawait sdk.connectAccount(window.ethereum, 8453);\n```\n\n**Security:** The private key stays in the user's wallet. The SDK only requests signatures when needed.\n\n### Option 2: Viem WalletClient (Recommended for Server Agents)\n\nUse a pre-configured viem WalletClient. This is the recommended approach for server-side agents as it allows integration with secure key management solutions.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\n\u002F\u002F Create wallet client with your preferred key management\n\u002F\u002F Option A: From environment variable (simple but requires secure env management)\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\n\n\u002F\u002F Option B: From KMS (AWS, GCP, etc.) - recommended for production\n\u002F\u002F const account = await getAccountFromKMS();\n\n\u002F\u002F Option C: From Wallet-as-a-Service (Turnkey, Privy, etc.)\n\u002F\u002F const account = await turnkeyClient.getAccount();\n\nconst walletClient = createWalletClient({\n  account,\n  chain: base,\n  transport: http(),\n});\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F Connect using the WalletClient\nawait sdk.connectAccount(walletClient, 8453);\n```\n\n**Security:** The WalletClient abstraction allows you to integrate with secure key management solutions like:\n- **AWS KMS** \u002F **GCP Cloud KMS** — Hardware-backed key storage\n- **Turnkey** \u002F **Privy** \u002F **Dynamic** — Wallet-as-a-Service providers\n- **Hardware wallets** — Via WalletConnect or similar\n\n### Option 3: Private Key String (Development Only)\n\nDirect private key usage.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F WARNING: Only use for development. Never hardcode private keys in production.\nawait sdk.connectAccount(process.env.PRIVATE_KEY, 8453);\n```\n\n**Security Warning:** Raw private keys in environment variables are a security risk. For production autonomous agents, use Option 2 with a proper key management solution.\n\n### Security Comparison\n\n| Method | Security Level | Use Case |\n|--------|---------------|----------|\n| Wallet Provider | High | Browser dApps, user-facing apps |\n| WalletClient + KMS | High | Production server agents |\n| WalletClient + WaaS | High | Production server agents |\n| Private Key String | Low | Development\u002Ftesting only |\n\n## Step-by-Step\n\n### 1. Connect to Zyfai\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F For browser: use wallet provider\nawait sdk.connectAccount(window.ethereum, 8453);\n\n\u002F\u002F For server: use WalletClient (see Wallet Connection Options above)\nconst walletClient = createWalletClient({\n  account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n  chain: base,\n  transport: http(),\n});\nawait sdk.connectAccount(walletClient, 8453);\n```\n\n### 2. Deploy Subaccount\n\n```typescript\nconst userAddress = \"0x...\"; \u002F\u002F User's EOA (NOT the subaccount address!)\nconst chainId = 8453; \u002F\u002F Base\n\n\u002F\u002F Check if subaccount exists\nconst wallet = await sdk.getSmartWalletAddress(userAddress, chainId);\nconsole.log(`Subaccount: ${wallet.address}`);\nconsole.log(`Deployed: ${wallet.isDeployed}`);\n\n\u002F\u002F Deploy if needed\nif (!wallet.isDeployed) {\n  const result = await sdk.deploySafe(userAddress, chainId, \"conservative\");\n  console.log(\"Subaccount deployed:\", result.safeAddress);\n}\n```\n\n**Strategies:**\n- `\"conservative\"` — Stable yield, lower risk\n- `\"aggressive\"` — Higher yield, higher risk\n\n### 3. Enable Yield Optimization\n\n```typescript\nawait sdk.createSessionKey(userAddress, chainId);\n\n\u002F\u002F Always verify the session key was activated\nconst user = await sdk.getUserDetails();\nif (!user.user.hasActiveSessionKey) {\n  \u002F\u002F Session key not active — retry the process\n  console.log(\"Session key not active, retrying...\");\n  await sdk.createSessionKey(userAddress, chainId);\n  \n  \u002F\u002F Verify again\n  const userRetry = await sdk.getUserDetails();\n  if (!userRetry.user.hasActiveSessionKey) {\n    throw new Error(\"Session key activation failed after retry. Contact support.\");\n  }\n}\nconsole.log(\"Session key active:\", user.user.hasActiveSessionKey);\n```\n\nThis allows Zyfai to rebalance funds automatically. Session keys **cannot** withdraw to arbitrary addresses — only optimize within the protocol.\n\n> **Important:** Always verify the session key is active by checking `getUserDetails().user.hasActiveSessionKey` after calling `createSessionKey`. If it returns `false`, retry the process. A session key must be active for automated yield optimization to work.\n\n### 4. Deposit Funds\n\n```typescript\n\u002F\u002F Deposit 10 USDC (6 decimals)\nawait sdk.depositFunds(userAddress, chainId, \"10000000\");\n```\n\nFunds move from EOA -> Subaccount and start earning yield immediately.\n\n### 5. Withdraw Funds\n\n```typescript\n\u002F\u002F Withdraw everything\nawait sdk.withdrawFunds(userAddress, chainId);\n\n\u002F\u002F Or withdraw partial (5 USDC)\nawait sdk.withdrawFunds(userAddress, chainId, \"5000000\");\n```\n\nFunds return to the user's EOA. Withdrawals are processed asynchronously.\n\n### 6. Disconnect\n\n```typescript\nawait sdk.disconnectAccount();\n```\n\n## Complete Example\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\nasync function startEarningYield(userAddress: string) {\n  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });\n  const chainId = 8453; \u002F\u002F Base\n  \n  \u002F\u002F Connect using WalletClient (recommended for server agents)\n  const walletClient = createWalletClient({\n    account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n    chain: base,\n    transport: http(),\n  });\n  await sdk.connectAccount(walletClient, chainId);\n  \n  \u002F\u002F Deploy subaccount if needed (always pass EOA as userAddress)\n  const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);\n  if (!wallet.isDeployed) {\n    await sdk.deploySafe(userAddress, chainId, \"conservative\");\n    console.log(\"Subaccount created:\", wallet.address);\n  }\n  \n  \u002F\u002F Enable automated optimization\n  await sdk.createSessionKey(userAddress, chainId);\n  \n  \u002F\u002F Verify session key is active\n  const user = await sdk.getUserDetails();\n  if (!user.user.hasActiveSessionKey) {\n    console.log(\"Session key not active, retrying...\");\n    await sdk.createSessionKey(userAddress, chainId);\n    const userRetry = await sdk.getUserDetails();\n    if (!userRetry.user.hasActiveSessionKey) {\n      throw new Error(\"Session key activation failed. Contact support.\");\n    }\n  }\n  \n  \u002F\u002F Deposit 100 USDC\n  await sdk.depositFunds(userAddress, chainId, \"100000000\");\n  console.log(\"Deposited! Now earning yield.\");\n  \n  await sdk.disconnectAccount();\n}\n\nasync function withdrawYield(userAddress: string, amount?: string) {\n  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });\n  const chainId = 8453; \u002F\u002F Base\n  \n  \u002F\u002F Connect using WalletClient\n  const walletClient = createWalletClient({\n    account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n    chain: base,\n    transport: http(),\n  });\n  await sdk.connectAccount(walletClient, chainId);\n  \n  \u002F\u002F Withdraw funds (pass EOA as userAddress)\n  if (amount) {\n    \u002F\u002F Partial withdrawal\n    await sdk.withdrawFunds(userAddress, chainId, amount);\n    console.log(`Withdrawn ${amount} (6 decimals) to EOA`);\n  } else {\n    \u002F\u002F Full withdrawal\n    await sdk.withdrawFunds(userAddress, chainId);\n    console.log(\"Withdrawn all funds to EOA\");\n  }\n  \n  await sdk.disconnectAccount();\n}\n```\n\n## API Reference\n\n| Method | Params | Description |\n|--------|--------|-------------|\n| `connectAccount` | `(walletClientOrProvider, chainId)` | Authenticate with Zyfai |\n| `getSmartWalletAddress` | `(userAddress, chainId)` | Get subaccount address & status |\n| `deploySafe` | `(userAddress, chainId, strategy)` | Create subaccount |\n| `createSessionKey` | `(userAddress, chainId)` | Enable auto-optimization |\n| `depositFunds` | `(userAddress, chainId, amount)` | Deposit USDC (6 decimals) |\n| `withdrawFunds` | `(userAddress, chainId, amount?)` | Withdraw (all if no amount) |\n| `getPositions` | `(userAddress, chainId?)` | Get active DeFi positions |\n| `getAvailableProtocols` | `(chainId)` | Get available protocols & pools |\n| `getAPYPerStrategy` | `(crossChain?, days?, strategyType?)` | Get APY for conservative\u002Faggressive strategies |\n| `getUserDetails` | `()` | Get authenticated user details |\n| `getOnchainEarnings` | `(walletAddress)` | Get earnings data |\n| `updateUserProfile` | `(params)` | Update strategy, protocols, splitting, cross-chain settings |\n| `registerAgentOnIdentityRegistry` | `(smartWallet, chainId)` | Register agent on ERC-8004 Identity Registry |\n| `disconnectAccount` | `()` | End session |\n\n**Note:** All methods that take `userAddress` expect the **EOA address**, not the subaccount\u002FSafe address.\n\n## Data Methods\n\n### getPositions\n\nGet all active DeFi positions for a user across protocols. Optionally filter by chain.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| userAddress | string | Yes | User's EOA address |\n| chainId | SupportedChainId | No | Optional: Filter by specific chain ID |\n\n**Example:**\n\n```typescript\n\u002F\u002F Get all positions across all chains\nconst positions = await sdk.getPositions(\"0xUser...\");\n\n\u002F\u002F Get positions on Arbitrum only\nconst arbPositions = await sdk.getPositions(\"0xUser...\", 42161);\n```\n\n**Returns:**\n\n```typescript\ninterface PositionsResponse {\n  success: boolean;\n  userAddress: string;\n  positions: Position[];\n}\n```\n\n### getAvailableProtocols\n\nGet available DeFi protocols and pools for a specific chain with APY data.\n\n```typescript\nconst protocols = await sdk.getAvailableProtocols(42161); \u002F\u002F Arbitrum\n\nprotocols.protocols.forEach((protocol) => {\n  console.log(`${protocol.name} (ID: ${protocol.id})`);\n  if (protocol.pools) {\n    protocol.pools.forEach((pool) => {\n      console.log(`  Pool: ${pool.name} - APY: ${pool.apy || \"N\u002FA\"}%`);\n    });\n  }\n});\n```\n\nReturns:\n```typescript\ninterface ProtocolsResponse {\n  success: boolean;\n  chainId: SupportedChainId;\n  protocols: Protocol[];\n}\n```\n\n### getUserDetails\n\nGet current authenticated user details including smart wallet, chains, protocols, and settings. Requires SIWE authentication.\n\n```typescript\nawait sdk.connectAccount(walletClient, chainId);\nconst user = await sdk.getUserDetails();\n\nconsole.log(\"Smart Wallet:\", user.user.smartWallet);\nconsole.log(\"Chains:\", user.user.chains);\nconsole.log(\"Has Active Session:\", user.user.hasActiveSessionKey);\n```\n\nReturns:\n```typescript\ninterface UserDetailsResponse {\n  success: boolean;\n  user: {\n    id: string;\n    address: string;\n    smartWallet?: string;\n    chains: number[];\n    protocols: Protocol[];\n    hasActiveSessionKey: boolean;\n    email?: string;\n    strategy?: string;\n    telegramId?: string;\n    walletType?: string;\n    autoSelectProtocols: boolean;\n    autocompounding?: boolean;\n    omniAccount?: boolean;\n    crosschainStrategy?: boolean;\n    agentName?: string;\n    customization?: Record\u003Cstring, string[]>;\n  };\n}\n```\n\n### updateUserProfile\n\nUpdate the authenticated user's profile settings including strategy, protocols, splitting, and cross-chain options. Requires SIWE authentication.\n\n```typescript\nsdk.updateUserProfile(params: UpdateUserProfileRequest): Promise\u003CUpdateUserProfileResponse>\n```\n\n**Parameters:**\n\n```typescript\ninterface UpdateUserProfileRequest {\n  \u002F** Investment strategy: \"conservative\" for safer yields, \"aggressive\" for higher risk\u002Freward *\u002F\n  strategy?: \"conservative\" | \"aggressive\";\n\n  \u002F** Array of protocol IDs to use for yield optimization *\u002F\n  protocols?: string[];\n\n  \u002F** Enable omni-account feature for cross-chain operations *\u002F\n  omniAccount?: boolean;\n\n  \u002F** Enable automatic compounding of earned yields (default: true) *\u002F\n  autocompounding?: boolean;\n\n  \u002F** Custom name for your agent *\u002F\n  agentName?: string;\n\n  \u002F** Enable cross-chain strategy execution *\u002F\n  crosschainStrategy?: boolean;\n\n  \u002F** Enable position splitting across multiple protocols *\u002F\n  splitting?: boolean;\n\n  \u002F** Minimum number of splits when position splitting is enabled (1-4) *\u002F\n  minSplits?: number;\n}\n```\n\n**Returns:**\n\n```typescript\ninterface UpdateUserProfileResponse {\n  success: boolean;\n  userId: string;\n  smartWallet?: string;\n  chains?: number[];\n  strategy?: string;\n  protocols?: string[];\n  omniAccount?: boolean;\n  autocompounding?: boolean;\n  agentName?: string;\n  crosschainStrategy?: boolean;\n  executorProxy?: boolean;\n  splitting?: boolean;\n  minSplits?: number;\n}\n```\n\n**Examples:**\n\n```typescript\n\u002F\u002F Update strategy from conservative to aggressive\nawait sdk.updateUserProfile({\n  strategy: \"aggressive\",\n});\n\n\u002F\u002F Configure specific protocols\nconst protocolsResponse = await sdk.getAvailableProtocols(8453);\nconst selectedProtocols = protocolsResponse.protocols\n  .filter(p => [\"Aave\", \"Compound\", \"Moonwell\"].includes(p.name))\n  .map(p => p.id);\n\nawait sdk.updateUserProfile({\n  protocols: selectedProtocols,\n});\n\n\u002F\u002F Enable position splitting (distribute across multiple protocols)\nawait sdk.updateUserProfile({\n  splitting: true,\n  minSplits: 3, \u002F\u002F Split across at least 3 protocols\n});\n\n\u002F\u002F Verify changes\nconst userDetails = await sdk.getUserDetails();\nconsole.log(\"Strategy:\", userDetails.user.strategy);\nconsole.log(\"Splitting:\", userDetails.user.splitting);\n```\n\n> **Cross-chain strategies:** Only enable cross-chain when the user **explicitly requests** it. For cross-chain to work, **both** `crosschainStrategy` and `omniAccount` must be set to `true`. Never enable cross-chain settings by default.\n\n```typescript\n\u002F\u002F Enable cross-chain ONLY when explicitly requested by the user\nawait sdk.updateUserProfile({\n  crosschainStrategy: true,\n  omniAccount: true,\n});\n\n\u002F\u002F Now funds can be rebalanced across configured chains\nconst user = await sdk.getUserDetails();\nconsole.log(\"Operating on chains:\", user.user.chains);\n```\n\n**Notes:**\n- **Strategy:** Can be changed anytime. Subsequent rebalancing uses the new active strategy.\n- **Protocols:** Use `getAvailableProtocols(chainId)` to get valid protocol IDs before updating.\n- **Smart Splitting (minSplits = 1):** Default mode. To maximize returns, funds are automatically distributed across multiple DeFi pools — but only when beneficial. The system intelligently decides when splitting is advantageous based on current market conditions and opportunities. Funds may not split if no opportunity exists.\n- **Forced Splitting (minSplits > 1):** When `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.\n- **Cross-chain:** Requires **both** `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.\n- **Auto-compounding:** Enabled by default. When `true`, yields are reinvested automatically.\n- Smart wallet address, chains, and `executorProxy` cannot be updated via this method.\n\n### getAPYPerStrategy\n\nGet global APY by strategy type (conservative or aggressive), time period, and chain configuration. Use this to compare expected returns between strategies before deploying.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| crossChain | boolean | No | If `true`, returns APY for cross-chain strategies; if `false`, single-chain |\n| days | number | No | Period over which APY is calculated. One of `7`, `15`, `30`, `60` |\n| strategyType | string | No | Strategy risk profile. One of `'conservative'` or `'aggressive'` |\n\n**Example:**\n\n```typescript\n\u002F\u002F Get 7-day APY for conservative single-chain strategy\nconst conservativeApy = await sdk.getAPYPerStrategy(false, 7, 'conservative');\nconsole.log(\"Conservative APY:\", conservativeApy.data);\n\n\u002F\u002F Get 30-day APY for aggressive cross-chain strategy\nconst aggressiveApy = await sdk.getAPYPerStrategy(true, 30, 'aggressive');\nconsole.log(\"Aggressive APY:\", aggressiveApy.data);\n\n\u002F\u002F Compare strategies\nconst conservative = await sdk.getAPYPerStrategy(false, 30, 'conservative');\nconst aggressive = await sdk.getAPYPerStrategy(false, 30, 'aggressive');\nconsole.log(`Conservative 30d APY: ${conservative.data[0]?.apy}%`);\nconsole.log(`Aggressive 30d APY: ${aggressive.data[0]?.apy}%`);\n```\n\n**Returns:**\n\n```typescript\ninterface APYPerStrategyResponse {\n  success: boolean;\n  count: number;\n  data: APYPerStrategy[];\n}\n\ninterface APYPerStrategy {\n  strategyType: string;\n  apy: number;\n  period: number;\n  crossChain: boolean;\n}\n```\n\n### getOnchainEarnings\n\nGet onchain earnings for a wallet including total, current, and lifetime earnings.\n\n```typescript\nconst earnings = await sdk.getOnchainEarnings(smartWalletAddress);\n\nconsole.log(\"Total earnings:\", earnings.data.totalEarnings);\nconsole.log(\"Current earnings:\", earnings.data.currentEarnings);\nconsole.log(\"Lifetime earnings:\", earnings.data.lifetimeEarnings);\n```\n\nReturns:\n```typescript\ninterface OnchainEarningsResponse {\n  success: boolean;\n  data: {\n    walletAddress: string;\n    totalEarnings: number;\n    currentEarnings: number;\n    lifetimeEarnings: number;\n    unrealizedEarnings?: number;\n    currentEarningsByChain?: Record\u003Cstring, number>;\n    unrealizedEarningsByChain?: Record\u003Cstring, number>;\n    lastCheckTimestamp?: string;\n  };\n}\n```\n\n### registerAgentOnIdentityRegistry (ERC-8004)\n\nRegister 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.\n\n**Supported Chains:**\n\n| Chain | Chain ID |\n|-------|----------|\n| Base | 8453 |\n| Arbitrum | 42161 |\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| smartWallet | string | Yes | The Zyfai deployed smart wallet address to register as an agent |\n| chainId | SupportedChainId | Yes | Chain ID (only 8453 or 42161) |\n\n**Example:**\n\n```typescript\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\" });\nawait sdk.connectAccount(walletClient, 8453);\n\n\u002F\u002F Get smart wallet address\nconst walletInfo = await sdk.getSmartWalletAddress(userAddress, 8453);\nconst smartWallet = walletInfo.address;\n\n\u002F\u002F Register agent on Identity Registry\nconst result = await sdk.registerAgentOnIdentityRegistry(smartWallet, 8453);\n\nconsole.log(\"Registration successful:\");\nconsole.log(\"  Tx Hash:\", result.txHash);\nconsole.log(\"  Chain ID:\", result.chainId);\nconsole.log(\"  Smart Wallet:\", result.smartWallet);\n```\n\n**Returns:**\n\n```typescript\ninterface RegisterAgentResponse {\n  success: boolean;\n  txHash: string;\n  chainId: number;\n  smartWallet: string;\n}\n```\n\n**How It Works:**\n\n1. Fetches a `tokenUri` from the Zyfai API (agent metadata stored on IPFS)\n2. Encodes the `register(tokenUri)` call for the Identity Registry contract\n3. Sends the transaction from the connected wallet\n4. Waits for on-chain confirmation\n\n## Security\n\n- **Non-custodial** — User's EOA owns the subaccount\n- **Session keys are limited** — Can rebalance, cannot withdraw elsewhere\n- **Deterministic** — Same EOA = same subaccount on every chain\n- **Flexible key management** — Use wallet providers, WalletClients, or KMS integrations\n\n### Key Management Best Practices\n\nFor **production autonomous agents**, we recommend:\n\n1. **Use a WalletClient** with a secure key source (not raw private keys)\n2. **Integrate with KMS** (AWS KMS, GCP Cloud KMS) for hardware-backed key storage\n3. **Consider Wallet-as-a-Service** providers like Turnkey, Privy, or Dynamic\n4. **Never hardcode** private keys in source code\n5. **Rotate keys** periodically and implement key revocation procedures\n\n## Troubleshooting\n\n### Subaccount address mismatch across chains\n\nThe subaccount address should be **identical** across all chains for the same EOA. If you see different addresses:\n\n```typescript\n\u002F\u002F Check addresses on both chains\nconst baseWallet = await sdk.getSmartWalletAddress(userAddress, 8453);\nconst arbWallet = await sdk.getSmartWalletAddress(userAddress, 42161);\n\nif (baseWallet.address !== arbWallet.address) {\n  console.error(\"Address mismatch! Contact support.\");\n}\n```\n\n**If addresses don't match:**\n1. Try redeploying on the affected chain\n2. If the issue persists, contact support on Telegram: [@paul_zyfai](https:\u002F\u002Ft.me\u002Fpaul_zyfai)\n\n### \"Deposit address not found\" error\n\nThis means the wallet isn't registered in the backend. Solution:\n1. Call `deploySafe()` first — even if the Safe is already deployed on-chain, this registers it with the backend\n2. Then retry `createSessionKey()`\n\n### \"Invalid signature\" error\n\nThis typically means:\n- The wallet\u002Fsigner doesn't match the EOA you're passing\n- The Safe address on-chain doesn't match what the SDK expects\n\nVerify you're using the correct wallet for the EOA.\n\n## Resources\n\n- **Get API Key:** [sdk.zyf.ai](https:\u002F\u002Fsdk.zyf.ai) or programmatically via `POST \u002Fapi\u002Fsdk-api-keys\u002Fcreate`\n- **Docs:** [docs.zyf.ai](https:\u002F\u002Fdocs.zyf.ai)\n- **Demo:** [github.com\u002Fondefy\u002Fzyfai-sdk-demo](https:\u002F\u002Fgithub.com\u002Fondefy\u002Fzyfai-sdk-demo)\n- **MCP Server:** [mcp.zyf.ai](https:\u002F\u002Fmcp.zyf.ai\u002Fmcp) — Use with Claude or other MCP-compatible agents\n- **Agent Registration:** [zyf.ai\u002F.well-known\u002Fagent-registration.json](https:\u002F\u002Fwww.zyf.ai\u002F.well-known\u002Fagent-registration.json)\n","# Zyfai — Yield for Any Wallet\n\nLet any Ethereum wallet access a yield-generating account.\n\n## What This Does\n\nWhen a user wants to **earn yield** on their crypto, Zyfai creates a **deterministic 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.\n\n```\n┌─────────────────┐      ┌──────────────────────┐\n│   User's EOA    │ ───► │  Zyfai Subaccount    │\n│  (their wallet) │      │  (Safe smart wallet) │\n│                 │      │                      │\n│  Owns & controls│      │  • Auto-rebalancing  │\n│                 │      │  • Yield optimization│\n│                 │      │  • Non-custodial     │\n└─────────────────┘      └──────────────────────┘\n```\n\n**Key points:**\n- The subaccount is **owned by the user's EOA** — only they can withdraw\n- Session keys allow **automated rebalancing** but cannot withdraw to other addresses\n- Same EOA = same subaccount address across all chains\n\n## The Flow\n\n```\n1. DEPLOY    →  Create a deterministic subaccount linked to user's wallet\n2. SESSION   →  Enable automated yield optimization  \n3. DEPOSIT   →  Send funds to subaccount (starts earning)\n4. WITHDRAW  →  Pull funds back to wallet (anytime)\n```\n\n## Prerequisites\n\n- **API Key** — Get one programmatically (see below) or manually at [sdk.zyf.ai](https:\u002F\u002Fsdk.zyf.ai)\n- **Wallet Connection** — Either a wallet provider (browser) or secure key management (server)\n- **Node.js 18+**\n\n```bash\nnpm install @zyfai\u002Fsdk viem\n```\n\n### Programmatic API Key Creation (Agent-Native)\n\nAgents can create their own API key without human intervention. You need the wallet address (public key) of the agent.\n\n```bash\nPOST https:\u002F\u002Fsdk.zyf.ai\u002Fapi\u002Fsdk-api-keys\u002Fcreate\nContent-Type: application\u002Fjson\n\n{\n  \"clientName\": \"my-agent\",\n  \"walletAddress\": \"0x...\",\n  \"email\": \"agent@example.com\"\n}\n```\n\n**Response:**\n```json\n{\n  \"success\": true,\n  \"message\": \"SDK API key created successfully. Store the apiKey securely - it cannot be retrieved later!\",\n  \"data\": {\n    \"id\": \"936...\",\n    \"apiKey\": \"zyfai_361ad41d083c2fe.....\",\n    \"keyPrefix\": \"zyfai_361ad4\",\n    \"clientName\": \"my-agent\",\n    \"ownerWalletAddress\": \"0x...\"\n  }\n}\n```\n\n> **Important:** Store the `apiKey` securely — it cannot be retrieved later. The key is linked to the provided wallet address.\n\n## Supported Chains\n\n| Chain    | ID    |\n|----------|-------|\n| Arbitrum | 42161 |\n| Base     | 8453  |\n| Plasma   | 9745  |\n\n## Important: Always Use EOA Address\n\nWhen calling SDK methods, **always pass the EOA address** (the user's wallet address) as `userAddress` — never the subaccount\u002FSafe address. The SDK derives the subaccount address automatically from the EOA.\n\n## Wallet Connection Options\n\nThe SDK supports multiple ways to connect a wallet. Choose based on your security requirements and deployment context.\n\n### Option 1: Wallet Provider (Recommended for Browser\u002FdApps)\n\nUse an injected wallet provider like MetaMask. The private key never leaves the user's wallet.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F Connect using injected wallet provider (MetaMask, WalletConnect, etc.)\nawait sdk.connectAccount(window.ethereum, 8453);\n```\n\n**Security:** The private key stays in the user's wallet. The SDK only requests signatures when needed.\n\n### Option 2: Viem WalletClient (Recommended for Server Agents)\n\nUse a pre-configured viem WalletClient. This is the recommended approach for server-side agents as it allows integration with secure key management solutions.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\n\u002F\u002F Create wallet client with your preferred key management\n\u002F\u002F Option A: From environment variable (simple but requires secure env management)\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\n\n\u002F\u002F Option B: From KMS (AWS, GCP, etc.) - recommended for production\n\u002F\u002F const account = await getAccountFromKMS();\n\n\u002F\u002F Option C: From Wallet-as-a-Service (Turnkey, Privy, etc.)\n\u002F\u002F const account = await turnkeyClient.getAccount();\n\nconst walletClient = createWalletClient({\n  account,\n  chain: base,\n  transport: http(),\n});\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F Connect using the WalletClient\nawait sdk.connectAccount(walletClient, 8453);\n```\n\n**Security:** The WalletClient abstraction allows you to integrate with secure key management solutions like:\n- **AWS KMS** \u002F **GCP Cloud KMS** — Hardware-backed key storage\n- **Turnkey** \u002F **Privy** \u002F **Dynamic** — Wallet-as-a-Service providers\n- **Hardware wallets** — Via WalletConnect or similar\n\n### Option 3: Private Key String (Development Only)\n\nDirect private key usage.\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F WARNING: Only use for development. Never hardcode private keys in production.\nawait sdk.connectAccount(process.env.PRIVATE_KEY, 8453);\n```\n\n**Security Warning:** Raw private keys in environment variables are a security risk. For production autonomous agents, use Option 2 with a proper key management solution.\n\n### Security Comparison\n\n| Method | Security Level | Use Case |\n|--------|---------------|----------|\n| Wallet Provider | High | Browser dApps, user-facing apps |\n| WalletClient + KMS | High | Production server agents |\n| WalletClient + WaaS | High | Production server agents |\n| Private Key String | Low | Development\u002Ftesting only |\n\n## Step-by-Step\n\n### 1. Connect to Zyfai\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\", referralSource: \"openclaw-skill\" });\n\n\u002F\u002F For browser: use wallet provider\nawait sdk.connectAccount(window.ethereum, 8453);\n\n\u002F\u002F For server: use WalletClient (see Wallet Connection Options above)\nconst walletClient = createWalletClient({\n  account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n  chain: base,\n  transport: http(),\n});\nawait sdk.connectAccount(walletClient, 8453);\n```\n\n### 2. Deploy Subaccount\n\n```typescript\nconst userAddress = \"0x...\"; \u002F\u002F User's EOA (NOT the subaccount address!)\nconst chainId = 8453; \u002F\u002F Base\n\n\u002F\u002F Check if subaccount exists\nconst wallet = await sdk.getSmartWalletAddress(userAddress, chainId);\nconsole.log(`Subaccount: ${wallet.address}`);\nconsole.log(`Deployed: ${wallet.isDeployed}`);\n\n\u002F\u002F Deploy if needed\nif (!wallet.isDeployed) {\n  const result = await sdk.deploySafe(userAddress, chainId, \"conservative\");\n  console.log(\"Subaccount deployed:\", result.safeAddress);\n}\n```\n\n**Strategies:**\n- `\"conservative\"` — Stable yield, lower risk\n- `\"aggressive\"` — Higher yield, higher risk\n\n### 3. Enable Yield Optimization\n\n```typescript\nawait sdk.createSessionKey(userAddress, chainId);\n\n\u002F\u002F Always verify the session key was activated\nconst user = await sdk.getUserDetails();\nif (!user.user.hasActiveSessionKey) {\n  \u002F\u002F Session key not active — retry the process\n  console.log(\"Session key not active, retrying...\");\n  await sdk.createSessionKey(userAddress, chainId);\n  \n  \u002F\u002F Verify again\n  const userRetry = await sdk.getUserDetails();\n  if (!userRetry.user.hasActiveSessionKey) {\n    throw new Error(\"Session key activation failed after retry. Contact support.\");\n  }\n}\nconsole.log(\"Session key active:\", user.user.hasActiveSessionKey);\n```\n\nThis allows Zyfai to rebalance funds automatically. Session keys **cannot** withdraw to arbitrary addresses — only optimize within the protocol.\n\n> **Important:** Always verify the session key is active by checking `getUserDetails().user.hasActiveSessionKey` after calling `createSessionKey`. If it returns `false`, retry the process. A session key must be active for automated yield optimization to work.\n\n### 4. Deposit Funds\n\n```typescript\n\u002F\u002F Deposit 10 USDC (6 decimals)\nawait sdk.depositFunds(userAddress, chainId, \"10000000\");\n```\n\nFunds move from EOA -> Subaccount and start earning yield immediately.\n\n### 5. Withdraw Funds\n\n```typescript\n\u002F\u002F Withdraw everything\nawait sdk.withdrawFunds(userAddress, chainId);\n\n\u002F\u002F Or withdraw partial (5 USDC)\nawait sdk.withdrawFunds(userAddress, chainId, \"5000000\");\n```\n\nFunds return to the user's EOA. Withdrawals are processed asynchronously.\n\n### 6. Disconnect\n\n```typescript\nawait sdk.disconnectAccount();\n```\n\n## Complete Example\n\n```typescript\nimport { ZyfaiSDK } from \"@zyfai\u002Fsdk\";\nimport { createWalletClient, http } from \"viem\";\nimport { base } from \"viem\u002Fchains\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\n\nasync function startEarningYield(userAddress: string) {\n  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });\n  const chainId = 8453; \u002F\u002F Base\n  \n  \u002F\u002F Connect using WalletClient (recommended for server agents)\n  const walletClient = createWalletClient({\n    account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n    chain: base,\n    transport: http(),\n  });\n  await sdk.connectAccount(walletClient, chainId);\n  \n  \u002F\u002F Deploy subaccount if needed (always pass EOA as userAddress)\n  const wallet = await sdk.getSmartWalletAddress(userAddress, chainId);\n  if (!wallet.isDeployed) {\n    await sdk.deploySafe(userAddress, chainId, \"conservative\");\n    console.log(\"Subaccount created:\", wallet.address);\n  }\n  \n  \u002F\u002F Enable automated optimization\n  await sdk.createSessionKey(userAddress, chainId);\n  \n  \u002F\u002F Verify session key is active\n  const user = await sdk.getUserDetails();\n  if (!user.user.hasActiveSessionKey) {\n    console.log(\"Session key not active, retrying...\");\n    await sdk.createSessionKey(userAddress, chainId);\n    const userRetry = await sdk.getUserDetails();\n    if (!userRetry.user.hasActiveSessionKey) {\n      throw new Error(\"Session key activation failed. Contact support.\");\n    }\n  }\n  \n  \u002F\u002F Deposit 100 USDC\n  await sdk.depositFunds(userAddress, chainId, \"100000000\");\n  console.log(\"Deposited! Now earning yield.\");\n  \n  await sdk.disconnectAccount();\n}\n\nasync function withdrawYield(userAddress: string, amount?: string) {\n  const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });\n  const chainId = 8453; \u002F\u002F Base\n  \n  \u002F\u002F Connect using WalletClient\n  const walletClient = createWalletClient({\n    account: privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`),\n    chain: base,\n    transport: http(),\n  });\n  await sdk.connectAccount(walletClient, chainId);\n  \n  \u002F\u002F Withdraw funds (pass EOA as userAddress)\n  if (amount) {\n    \u002F\u002F Partial withdrawal\n    await sdk.withdrawFunds(userAddress, chainId, amount);\n    console.log(`Withdrawn ${amount} (6 decimals) to EOA`);\n  } else {\n    \u002F\u002F Full withdrawal\n    await sdk.withdrawFunds(userAddress, chainId);\n    console.log(\"Withdrawn all funds to EOA\");\n  }\n  \n  await sdk.disconnectAccount();\n}\n```\n\n## API Reference\n\n| Method | Params | Description |\n|--------|--------|-------------|\n| `connectAccount` | `(walletClientOrProvider, chainId)` | Authenticate with Zyfai |\n| `getSmartWalletAddress` | `(userAddress, chainId)` | Get subaccount address & status |\n| `deploySafe` | `(userAddress, chainId, strategy)` | Create subaccount |\n| `createSessionKey` | `(userAddress, chainId)` | Enable auto-optimization |\n| `depositFunds` | `(userAddress, chainId, amount)` | Deposit USDC (6 decimals) |\n| `withdrawFunds` | `(userAddress, chainId, amount?)` | Withdraw (all if no amount) |\n| `getPositions` | `(userAddress, chainId?)` | Get active DeFi positions |\n| `getAvailableProtocols` | `(chainId)` | Get available protocols & pools |\n| `getAPYPerStrategy` | `(crossChain?, days?, strategyType?)` | Get APY for conservative\u002Faggressive strategies |\n| `getUserDetails` | `()` | Get authenticated user details |\n| `getOnchainEarnings` | `(walletAddress)` | Get earnings data |\n| `updateUserProfile` | `(params)` | Update strategy, protocols, splitting, cross-chain settings |\n| `registerAgentOnIdentityRegistry` | `(smartWallet, chainId)` | Register agent on ERC-8004 Identity Registry |\n| `disconnectAccount` | `()` | End session |\n\n**Note:** All methods that take `userAddress` expect the **EOA address**, not the subaccount\u002FSafe address.\n\n## Data Methods\n\n### getPositions\n\nGet all active DeFi positions for a user across protocols. Optionally filter by chain.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| userAddress | string | Yes | User's EOA address |\n| chainId | SupportedChainId | No | Optional: Filter by specific chain ID |\n\n**Example:**\n\n```typescript\n\u002F\u002F Get all positions across all chains\nconst positions = await sdk.getPositions(\"0xUser...\");\n\n\u002F\u002F Get positions on Arbitrum only\nconst arbPositions = await sdk.getPositions(\"0xUser...\", 42161);\n```\n\n**Returns:**\n\n```typescript\ninterface PositionsResponse {\n  success: boolean;\n  userAddress: string;\n  positions: Position[];\n}\n```\n\n### getAvailableProtocols\n\nGet available DeFi protocols and pools for a specific chain with APY data.\n\n```typescript\nconst protocols = await sdk.getAvailableProtocols(42161); \u002F\u002F Arbitrum\n\nprotocols.protocols.forEach((protocol) => {\n  console.log(`${protocol.name} (ID: ${protocol.id})`);\n  if (protocol.pools) {\n    protocol.pools.forEach((pool) => {\n      console.log(`  Pool: ${pool.name} - APY: ${pool.apy || \"N\u002FA\"}%`);\n    });\n  }\n});\n```\n\nReturns:\n```typescript\ninterface ProtocolsResponse {\n  success: boolean;\n  chainId: SupportedChainId;\n  protocols: Protocol[];\n}\n```\n\n### getUserDetails\n\nGet current authenticated user details including smart wallet, chains, protocols, and settings. Requires SIWE authentication.\n\n```typescript\nawait sdk.connectAccount(walletClient, chainId);\nconst user = await sdk.getUserDetails();\n\nconsole.log(\"Smart Wallet:\", user.user.smartWallet);\nconsole.log(\"Chains:\", user.user.chains);\nconsole.log(\"Has Active Session:\", user.user.hasActiveSessionKey);\n```\n\nReturns:\n```typescript\ninterface UserDetailsResponse {\n  success: boolean;\n  user: {\n    id: string;\n    address: string;\n    smartWallet?: string;\n    chains: number[];\n    protocols: Protocol[];\n    hasActiveSessionKey: boolean;\n    email?: string;\n    strategy?: string;\n    telegramId?: string;\n    walletType?: string;\n    autoSelectProtocols: boolean;\n    autocompounding?: boolean;\n    omniAccount?: boolean;\n    crosschainStrategy?: boolean;\n    agentName?: string;\n    customization?: Record\u003Cstring, string[]>;\n  };\n}\n```\n\n### updateUserProfile\n\nUpdate the authenticated user's profile settings including strategy, protocols, splitting, and cross-chain options. Requires SIWE authentication.\n\n```typescript\nsdk.updateUserProfile(params: UpdateUserProfileRequest): Promise\u003CUpdateUserProfileResponse>\n```\n\n**Parameters:**\n\n```typescript\ninterface UpdateUserProfileRequest {\n  \u002F** Investment strategy: \"conservative\" for safer yields, \"aggressive\" for higher risk\u002Freward *\u002F\n  strategy?: \"conservative\" | \"aggressive\";\n\n  \u002F** Array of protocol IDs to use for yield optimization *\u002F\n  protocols?: string[];\n\n  \u002F** Enable omni-account feature for cross-chain operations *\u002F\n  omniAccount?: boolean;\n\n  \u002F** Enable automatic compounding of earned yields (default: true) *\u002F\n  autocompounding?: boolean;\n\n  \u002F** Custom name for your agent *\u002F\n  agentName?: string;\n\n  \u002F** Enable cross-chain strategy execution *\u002F\n  crosschainStrategy?: boolean;\n\n  \u002F** Enable position splitting across multiple protocols *\u002F\n  splitting?: boolean;\n\n  \u002F** Minimum number of splits when position splitting is enabled (1-4) *\u002F\n  minSplits?: number;\n}\n```\n\n**Returns:**\n\n```typescript\ninterface UpdateUserProfileResponse {\n  success: boolean;\n  userId: string;\n  smartWallet?: string;\n  chains?: number[];\n  strategy?: string;\n  protocols?: string[];\n  omniAccount?: boolean;\n  autocompounding?: boolean;\n  agentName?: string;\n  crosschainStrategy?: boolean;\n  executorProxy?: boolean;\n  splitting?: boolean;\n  minSplits?: number;\n}\n```\n\n**Examples:**\n\n```typescript\n\u002F\u002F Update strategy from conservative to aggressive\nawait sdk.updateUserProfile({\n  strategy: \"aggressive\",\n});\n\n\u002F\u002F Configure specific protocols\nconst protocolsResponse = await sdk.getAvailableProtocols(8453);\nconst selectedProtocols = protocolsResponse.protocols\n  .filter(p => [\"Aave\", \"Compound\", \"Moonwell\"].includes(p.name))\n  .map(p => p.id);\n\nawait sdk.updateUserProfile({\n  protocols: selectedProtocols,\n});\n\n\u002F\u002F Enable position splitting (distribute across multiple protocols)\nawait sdk.updateUserProfile({\n  splitting: true,\n  minSplits: 3, \u002F\u002F Split across at least 3 protocols\n});\n\n\u002F\u002F Verify changes\nconst userDetails = await sdk.getUserDetails();\nconsole.log(\"Strategy:\", userDetails.user.strategy);\nconsole.log(\"Splitting:\", userDetails.user.splitting);\n```\n\n> **Cross-chain strategies:** Only enable cross-chain when the user **explicitly requests** it. For cross-chain to work, **both** `crosschainStrategy` and `omniAccount` must be set to `true`. Never enable cross-chain settings by default.\n\n```typescript\n\u002F\u002F Enable cross-chain ONLY when explicitly requested by the user\nawait sdk.updateUserProfile({\n  crosschainStrategy: true,\n  omniAccount: true,\n});\n\n\u002F\u002F Now funds can be rebalanced across configured chains\nconst user = await sdk.getUserDetails();\nconsole.log(\"Operating on chains:\", user.user.chains);\n```\n\n**Notes:**\n- **Strategy:** Can be changed anytime. Subsequent rebalancing uses the new active strategy.\n- **Protocols:** Use `getAvailableProtocols(chainId)` to get valid protocol IDs before updating.\n- **Smart Splitting (minSplits = 1):** Default mode. To maximize returns, funds are automatically distributed across multiple DeFi pools — but only when beneficial. The system intelligently decides when splitting is advantageous based on current market conditions and opportunities. Funds may not split if no opportunity exists.\n- **Forced Splitting (minSplits > 1):** When `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.\n- **Cross-chain:** Requires **both** `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.\n- **Auto-compounding:** Enabled by default. When `true`, yields are reinvested automatically.\n- Smart wallet address, chains, and `executorProxy` cannot be updated via this method.\n\n### getAPYPerStrategy\n\nGet global APY by strategy type (conservative or aggressive), time period, and chain configuration. Use this to compare expected returns between strategies before deploying.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| crossChain | boolean | No | If `true`, returns APY for cross-chain strategies; if `false`, single-chain |\n| days | number | No | Period over which APY is calculated. One of `7`, `15`, `30`, `60` |\n| strategyType | string | No | Strategy risk profile. One of `'conservative'` or `'aggressive'` |\n\n**Example:**\n\n```typescript\n\u002F\u002F Get 7-day APY for conservative single-chain strategy\nconst conservativeApy = await sdk.getAPYPerStrategy(false, 7, 'conservative');\nconsole.log(\"Conservative APY:\", conservativeApy.data);\n\n\u002F\u002F Get 30-day APY for aggressive cross-chain strategy\nconst aggressiveApy = await sdk.getAPYPerStrategy(true, 30, 'aggressive');\nconsole.log(\"Aggressive APY:\", aggressiveApy.data);\n\n\u002F\u002F Compare strategies\nconst conservative = await sdk.getAPYPerStrategy(false, 30, 'conservative');\nconst aggressive = await sdk.getAPYPerStrategy(false, 30, 'aggressive');\nconsole.log(`Conservative 30d APY: ${conservative.data[0]?.apy}%`);\nconsole.log(`Aggressive 30d APY: ${aggressive.data[0]?.apy}%`);\n```\n\n**Returns:**\n\n```typescript\ninterface APYPerStrategyResponse {\n  success: boolean;\n  count: number;\n  data: APYPerStrategy[];\n}\n\ninterface APYPerStrategy {\n  strategyType: string;\n  apy: number;\n  period: number;\n  crossChain: boolean;\n}\n```\n\n### getOnchainEarnings\n\nGet onchain earnings for a wallet including total, current, and lifetime earnings.\n\n```typescript\nconst earnings = await sdk.getOnchainEarnings(smartWalletAddress);\n\nconsole.log(\"Total earnings:\", earnings.data.totalEarnings);\nconsole.log(\"Current earnings:\", earnings.data.currentEarnings);\nconsole.log(\"Lifetime earnings:\", earnings.data.lifetimeEarnings);\n```\n\nReturns:\n```typescript\ninterface OnchainEarningsResponse {\n  success: boolean;\n  data: {\n    walletAddress: string;\n    totalEarnings: number;\n    currentEarnings: number;\n    lifetimeEarnings: number;\n    unrealizedEarnings?: number;\n    currentEarningsByChain?: Record\u003Cstring, number>;\n    unrealizedEarningsByChain?: Record\u003Cstring, number>;\n    lastCheckTimestamp?: string;\n  };\n}\n```\n\n### registerAgentOnIdentityRegistry (ERC-8004)\n\nRegister 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.\n\n**Supported Chains:**\n\n| Chain | Chain ID |\n|-------|----------|\n| Base | 8453 |\n| Arbitrum | 42161 |\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| smartWallet | string | Yes | The Zyfai deployed smart wallet address to register as an agent |\n| chainId | SupportedChainId | Yes | Chain ID (only 8453 or 42161) |\n\n**Example:**\n\n```typescript\nconst sdk = new ZyfaiSDK({ apiKey: \"your-api-key\" });\nawait sdk.connectAccount(walletClient, 8453);\n\n\u002F\u002F Get smart wallet address\nconst walletInfo = await sdk.getSmartWalletAddress(userAddress, 8453);\nconst smartWallet = walletInfo.address;\n\n\u002F\u002F Register agent on Identity Registry\nconst result = await sdk.registerAgentOnIdentityRegistry(smartWallet, 8453);\n\nconsole.log(\"Registration successful:\");\nconsole.log(\"  Tx Hash:\", result.txHash);\nconsole.log(\"  Chain ID:\", result.chainId);\nconsole.log(\"  Smart Wallet:\", result.smartWallet);\n```\n\n**Returns:**\n\n```typescript\ninterface RegisterAgentResponse {\n  success: boolean;\n  txHash: string;\n  chainId: number;\n  smartWallet: string;\n}\n```\n\n**How It Works:**\n\n1. Fetches a `tokenUri` from the Zyfai API (agent metadata stored on IPFS)\n2. Encodes the `register(tokenUri)` call for the Identity Registry contract\n3. Sends the transaction from the connected wallet\n4. Waits for on-chain confirmation\n\n## Security\n\n- **Non-custodial** — User's EOA owns the subaccount\n- **Session keys are limited** — Can rebalance, cannot withdraw elsewhere\n- **Deterministic** — Same EOA = same subaccount on every chain\n- **Flexible key management** — Use wallet providers, WalletClients, or KMS integrations\n\n### Key Management Best Practices\n\nFor **production autonomous agents**, we recommend:\n\n1. **Use a WalletClient** with a secure key source (not raw private keys)\n2. **Integrate with KMS** (AWS KMS, GCP Cloud KMS) for hardware-backed key storage\n3. **Consider Wallet-as-a-Service** providers like Turnkey, Privy, or Dynamic\n4. **Never hardcode** private keys in source code\n5. **Rotate keys** periodically and implement key revocation procedures\n\n## Troubleshooting\n\n### Subaccount address mismatch across chains\n\nThe subaccount address should be **identical** across all chains for the same EOA. If you see different addresses:\n\n```typescript\n\u002F\u002F Check addresses on both chains\nconst baseWallet = await sdk.getSmartWalletAddress(userAddress, 8453);\nconst arbWallet = await sdk.getSmartWalletAddress(userAddress, 42161);\n\nif (baseWallet.address !== arbWallet.address) {\n  console.error(\"Address mismatch! Contact support.\");\n}\n```\n\n**If addresses don't match:**\n1. Try redeploying on the affected chain\n2. If the issue persists, contact support on Telegram: [@paul_zyfai](https:\u002F\u002Ft.me\u002Fpaul_zyfai)\n\n### \"Deposit address not found\" error\n\nThis means the wallet isn't registered in the backend. Solution:\n1. Call `deploySafe()` first — even if the Safe is already deployed on-chain, this registers it with the backend\n2. Then retry `createSessionKey()`\n\n### \"Invalid signature\" error\n\nThis typically means:\n- The wallet\u002Fsigner doesn't match the EOA you're passing\n- The Safe address on-chain doesn't match what the SDK expects\n\nVerify you're using the correct wallet for the EOA.\n\n## Resources\n\n- **Get API Key:** [sdk.zyf.ai](https:\u002F\u002Fsdk.zyf.ai) or programmatically via `POST \u002Fapi\u002Fsdk-api-keys\u002Fcreate`\n- **Docs:** [docs.zyf.ai](https:\u002F\u002Fdocs.zyf.ai)\n- **Demo:** [github.com\u002Fondefy\u002Fzyfai-sdk-demo](https:\u002F\u002Fgithub.com\u002Fondefy\u002Fzyfai-sdk-demo)\n- **MCP Server:** [mcp.zyf.ai](https:\u002F\u002Fmcp.zyf.ai\u002Fmcp) — Use with Claude or other MCP-compatible agents\n- **Agent Registration:** [zyf.ai\u002F.well-known\u002Fagent-registration.json](https:\u002F\u002Fwww.zyf.ai\u002F.well-known\u002Fagent-registration.json)\n",{"name":5,"description":7},"main","f9d3fe7cf9ac8f1ea63a0d96e98e1f510a3814db","skills\u002Fpauldefi\u002Fzyfai-sdk",1,"https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills","https:\u002F\u002Fgithub.com\u002Fjavimosch","intrane.fr","Building robust, open-source infrastructure for the commons. AI-leveraged, self-hosted, built to last.","2026-06-07 03:34:58",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add javimosch\u002Fopen-claw-skills --skill zyfai",{"tool":39,"command":40},"bunx","bunx skills add javimosch\u002Fopen-claw-skills --skill zyfai",{"tool":42,"command":43},"pnpm","pnpm dlx skills add javimosch\u002Fopen-claw-skills --skill zyfai","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fpauldefi\u002Fzyfai-sdk\u002FSKILL.md",true,[],[48,56,63,70,77,84],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":55},"01M778GGXG2VQ0YF31W2MKGMQZ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":55},"01M778G7BH8SBJ9FJ6C3G7CB1K","ceaser","Interact with the Ceaser privacy protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- shield, unshield, note management, and protocol queries. All ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). Ceaser is a privacy-preserving ETH wrapper using Noir\u002FUltraHonk zero-knowledge proofs on Base L2 (chain ID 8453).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":55},"01M778FYCJQZWFKKX5FYMK3S47","ceaser-send","Fully automated private ETH transfer via Ceaser Protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- all ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). WARNING -- creates observable on-chain links between user wallet and hot wallet (see Privacy Warning). Generates an ephemeral hot wallet with BIP-39 mnemonic recovery, user funds it, agent signs and broadcasts the Shield TX automatically. Exactly one manual step required (funding the hot wallet with ETH). Uses Noir\u002FUltraHonk zero-knowledge proofs.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser-send\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":55},"01M778FQQNSEYA3HJKZBPQ4M9Z","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":55},"01M778FGVZX7QA2TF9BFMM37FY","moldium","Post and manage content on the Moldium blog platform. Triggered by \"post to Moldium\", \"write a blog post\", \"publish an article\", etc.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyom45\u002Fmoldium\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":55},"01M778F88D8PQ9MQ0KNW2TJ8ZH","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, submit comments, search papers, and import papers. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, submitting paper reviews, searching papers by title, or importing papers from arXiv URLs via API at http:\u002F\u002Fweakaccept.top:8000\u002F.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[]]