Skip to main content

Technical Reference

One-stop technical reference for the Zyfai SDK (@zyfai/sdk). This page is the canonical map of how the SDK is wired, what it exposes, and how to plug it into a backend, a frontend, or an AI agent. For per-method signatures see the Smart Wallet API and the Intelligence Layer.

Create your own api key on the SDK Dashboard

Architecture

The SDK is a thin TypeScript layer that bridges your app with two backend surfaces and an on-chain Safe smart account stack. Everything is exposed through a single class: ZyfaiSDK, organized into the Smart Wallet API (execution) and the Intelligence Layer (read-only engine access).

LayerResponsibilityVersioning
Execution APISafe deployment, session keys, deposits, withdrawals, transactions/api/v1
Data APIEarnings, opportunities, APY history, platform analytics/api/v2
On-chainSafe7579 smart accounts, ERC-4337 bundling, ERC-8004 identity

Installation

@zyfai/sdk is published on the public npm registry. viem is a required peer dependency.

# npm
npm install @zyfai/sdk viem

# pnpm
pnpm add @zyfai/sdk viem

# yarn
yarn add @zyfai/sdk viem

Requirements: Node 18+ or any modern browser. Your application domain must also be CORS-whitelisted on the Zyfai backend.

Configuration

SDKConfig

interface SDKConfig {
apiKey: string;
rpcUrls?: Partial<Record<SupportedChainId, string>>;
}
FieldTypeRequiredPurpose
apiKeystringYesProject key (zyfai_...) — get one at sdk.zyf.ai or programmatically
rpcUrlsPartial<Record<SupportedChainId, string>>NoCustom RPC endpoints per chain (defaults to public RPCs — override in production)

Supported chains

type SupportedChainId = 8453 | 42161 | 1;
ChainIDAssets
Base8453USDC, WETH
Arbitrum42161USDC, WETH
Ethereum Mainnet1USDC, WETH
import { getSupportedChainIds, isSupportedChain } from "@zyfai/sdk";

getSupportedChainIds(); // [8453, 42161, 1]
isSupportedChain(8453); // true

Environment variables

ZYFAI_API_KEY=zyfai_xxxxxxxxxxxxxxxx
PRIVATE_KEY=0x... # backend only

# Optional but recommended in production
BASE_RPC_URL=https://base-mainnet.g.alchemy.com/v2/...
ARBITRUM_RPC_URL=https://arb-mainnet.g.alchemy.com/v2/...
MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/...

Integration Patterns

The SDK runs in three flavors. Pick the one that matches your runtime.

Backend / Node.js (private key)

import { ZyfaiSDK } from "@zyfai/sdk";

const sdk = new ZyfaiSDK({
apiKey: process.env.ZYFAI_API_KEY!,
rpcUrls: {
8453: process.env.BASE_RPC_URL,
42161: process.env.ARBITRUM_RPC_URL,
1: process.env.MAINNET_RPC_URL,
},
});

await sdk.connectAccount(process.env.PRIVATE_KEY!, 42161);

Frontend (EIP-1193 provider)

Works with any EIP-1193 provider: wagmi, Reown AppKit, window.ethereum, web3-react.

import { ZyfaiSDK } from "@zyfai/sdk";

const sdk = new ZyfaiSDK({ apiKey: process.env.NEXT_PUBLIC_ZYFAI_API_KEY! });

await sdk.connectAccount(provider, 8453); // SIWE handshake is automatic

Headless analytics (no wallet)

Some methods only need the API key — useful for B2B dashboards, monitoring, billing.

const sdk = new ZyfaiSDK({ apiKey: process.env.ZYFAI_API_KEY! });

const wallets = await sdk.getSdkAllowedWallets();
const tvl = await sdk.getSdkKeyTVL();

Standard Flow

For Smart Wallet integrations, every consumer goes through the same four steps:

1. DEPLOY    sdk.deploySafe(eoa, chainId, strategy)
2. SESSION sdk.createSessionKey(eoa, chainId)
3. DEPOSIT sdk.depositFunds(eoa, chainId, amountInWei)
4. WITHDRAW sdk.withdrawFunds(eoa, chainId, amountInWei?)

Notes:

  • Always pass the EOA address as userAddress — never the Safe address. The SDK derives the Safe address deterministically.
  • Same EOA → same Safe address across all chains.
  • Withdrawals are processed asynchronously — poll sdk.getHistory() for status.

Strategies

deploySafe and updateUserProfile accept a strategy that drives the Intelligence Engine's risk profile.

StrategyRisk profileDefault
"conservative"Low-risk, stable yieldyes
"aggressive"Higher yield, higher riskno
await sdk.deploySafe(eoa, 8453, "conservative");
await sdk.updateUserProfile({ strategy: "aggressive" });

Session Keys

Session keys allow Zyfai's Intelligence Engine to rebalance the Safe on the user's behalf — within strict, enforced limits.

What a session key can do:

  • Move funds between approved pools on the same Safe
  • Trigger auto-compounding
  • Execute capital splitting across pools

What a session key cannot do:

  • Withdraw to any external address
  • Interact with contracts outside the curator-managed registry
  • Sign arbitrary calldata (every transaction is byte-validated by the Security Proxy Gateway)
const result = await sdk.createSessionKey(eoa, chainId);
if (!result.alreadyActive) {
console.log("Session key registered:", result.sessionActivation?.id);
}

See the Session Keys product page and Security Proxy Gateway for the full enforcement model.

Amount formatting

Token amounts for deposits and withdrawals use least decimal units (wei-style):

// For USDC (6 decimals), 100 USDC = 100 * 10^6
await sdk.depositFunds(eoa, 8453, "100000000");

Earnings values (totalEarningsByToken, totalEarningsByChain, daily_total_delta_by_token) are returned as decimal strings (e.g. "421.315354") — parse with parseFloat() when doing arithmetic.

AI-Agent Integration

The SDK is designed to be operated by an autonomous agent, not just a human-driven app.

  • Programmatic API key creation — agents can mint their own SDK key linked to their wallet, no human in the loop. See Agent Quickstart → Programmatic API Key Creation.
  • ERC-8004 identity — register the agent on-chain in the Identity Registry via registerAgentOnIdentityRegistry.
  • Compact single-page reference — the entire SDK surface is also exposed as a markdown skill at docs.zyf.ai/Skill.md, optimized for LLM context windows.

Type Safety

The SDK ships full TypeScript typings. Import types as needed:

import type {
SDKConfig,
SupportedChainId,
DeploySafeResponse,
SessionKeyResponse,
PositionsResponse,
UpdateUserProfileResponse,
OnchainEarningsResponse,
SimulateBestPositionsResponse,
} from "@zyfai/sdk";

Response Format

All SDK methods return consistent response objects:

{
success: boolean;
// ...method-specific fields
}

Error Handling

Strategy

  • API errors are returned as response objects with error / message fields when recoverable
  • Network failures and 5xx responses are surfaced as thrown Error instances and retried with exponential backoff
  • On-chain errors bubble up from the underlying signer (viem / wallet provider) — user rejections appear as standard provider errors
  • 401 responses trigger automatic re-authentication; persistent failure throws

Pattern

try {
await sdk.deploySafe(userAddress, chainId);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);

if (message.includes("already deployed")) return "Safe already exists.";
if (message.includes("User rejected")) return "Signing was rejected.";
if (message.includes("No account")) return "Call sdk.connectAccount() first.";
if (message.includes("Unsupported chain")) return "Chain must be 8453, 42161 or 1.";

throw error;
}

Common errors

MessageCause
No account connectedconnectAccount() not called or has not resolved
Unsupported chainchainId is not one of 8453, 42161, 1
already deployedSafe already exists for this EOA on this chain
User rejected requestUser declined the signature in their wallet
401 UnauthorizedAPI key invalid, expired, or wallet not whitelisted

Rate Limiting

API calls are rate-limited per project key. The SDK applies automatic retry with exponential backoff on transient failures (network, 5xx, 429).

Reporting Issues

Include in every report:

  • SDK version (@zyfai/sdk)
  • Runtime (Node version, browser, framework)
  • API key prefix only (e.g. zyfai_361ad4...) — never the full key
  • Error message and stack trace
  • Minimal reproduction steps
  • Expected vs actual behavior

Channels: GitHub Issues · Discord · Telegram · zyf.ai