# Giza Agent SDK > TypeScript SDK for autonomous DeFi yield optimization agents. > Package: @gizatech/agent-sdk ## Install ```bash npm install @gizatech/agent-sdk ``` ## Configuration ```typescript import { Giza, Chain } from '@gizatech/agent-sdk'; const giza = new Giza({ chain: Chain.BASE, // Required. Target blockchain. apiKey: 'giza_...', // Optional. Falls back to GIZA_API_KEY env var. partner: 'my-app', // Optional. Falls back to GIZA_PARTNER_NAME env var. apiUrl: 'https://...', // Optional. Falls back to GIZA_API_URL env var. timeout: 45000, // Optional. Request timeout in ms. Default: 45000. enableRetry: false, // Optional. Auto-retry failed requests. Default: false. }); ``` ### Chain Enum ```typescript enum Chain { DEVNET = -1, ETHEREUM = 1, POLYGON = 137, CHAIN_999 = 999, BASE = 8453, CHAIN_9745 = 9745, SEPOLIA = 11155111, ARBITRUM = 42161, BASE_SEPOLIA = 84532, } ``` ### Address Type ```typescript type Address = `0x${string}`; ``` ## Quick Start Complete working example: initialize, create agent, activate, monitor, withdraw. ```typescript import { Giza, Chain } from '@gizatech/agent-sdk'; import type { Address } from '@gizatech/agent-sdk'; const giza = new Giza({ chain: Chain.BASE }); const USDC: Address = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'; // 1. Create a smart account for the user const agent = await giza.createAgent(userEOA); console.log('Smart account:', agent.wallet); // 2. User deposits USDC to agent.wallet, then activate await agent.activate({ owner: userEOA, token: USDC, protocols: ['aave', 'compound', 'moonwell'], txHash: depositTxHash, }); // 3. Trigger optimization run await agent.run(); // 4. Monitor const portfolio = await agent.portfolio(); const { apr } = await agent.apr(); console.log(`Status: ${portfolio.status}, APR: ${apr}%`); // 5. Partial withdrawal await agent.withdraw('500000000'); // 500 USDC // 6. Full withdrawal (deactivation) await agent.withdraw(); const final = await agent.waitForDeactivation({ interval: 5000, timeout: 300000, onUpdate: (s) => console.log(s.status), }); ``` ## Giza Class The `Giza` class is the SDK entry point. It provides agent factory methods, chain-level queries, optimizer access, and system utilities. ### Agent Factory ```typescript // Get an Agent handle without making an API call (you already know the wallet) giza.agent(wallet: Address): Agent // Create a new smart account and return an Agent handle giza.createAgent(eoa: Address): Promise // Look up an existing smart account by EOA and return an Agent handle giza.getAgent(eoa: Address): Promise // Get full smart account info (address, status, metadata) giza.getSmartAccount(eoa: Address): Promise ``` ### Chain-Level Queries ```typescript // List protocols available for a token giza.protocols(token: Address): Promise<{ protocols: string[] }> // Get supply data for protocols supporting a token giza.protocolSupply(token: Address): Promise // List supported tokens on the configured chain giza.tokens(): Promise // Get platform statistics giza.stats(): Promise // Get total value locked giza.tvl(): Promise ``` ### Optimizer ```typescript // Get optimal allocation for given capital and constraints giza.optimize(opts: OptimizeOptions): Promise ``` ### System ```typescript // Health check giza.health(): Promise // Get global API configuration giza.getApiConfig(): Promise // List all supported chains giza.chains(): Promise // Get the configured chain giza.getChain(): Chain // Get the API base URL giza.getApiUrl(): string ``` ## Agent Class The `Agent` class represents a wallet-scoped smart account. All methods operate on the agent's wallet address. Get an Agent via `giza.createAgent()`, `giza.getAgent()`, or `giza.agent()`. ```typescript agent.wallet // readonly Address - the smart account address ``` ### Lifecycle ```typescript // Activate the agent with initial deposit agent.activate(opts: { owner: Address; token: Address; protocols: string[]; txHash: string; constraints?: ConstraintConfig[]; }): Promise // Deactivate and begin withdrawal agent.deactivate(opts?: { transfer?: boolean; }): Promise // Record a top-up deposit agent.topUp(txHash: string): Promise // Trigger an optimization run agent.run(): Promise ``` ### Monitoring ```typescript // Get current portfolio info (status, protocols, balances) agent.portfolio(): Promise // Get performance chart data agent.performance(opts?: { from?: string; // ISO date string }): Promise // Get APR data agent.apr(opts?: { startDate?: string; endDate?: string; useExactEndDate?: boolean; }): Promise // Get APR broken down by token agent.aprByTokens(period?: Period): Promise // Get deposit history agent.deposits(): Promise ``` ### Paginated Methods These return a `Paginator` (see Paginator section below). ```typescript // Transaction history agent.transactions(opts?: { limit?: number; sort?: SortOrder; }): Paginator // Execution history agent.executions(opts?: { limit?: number; sort?: SortOrder; }): Paginator // Logs for a specific execution agent.executionLogs(executionId: string, opts?: { limit?: number; sort?: SortOrder; }): Paginator // All agent logs agent.logs(opts?: { limit?: number; sort?: SortOrder; }): Paginator // Reward events agent.rewards(opts?: { limit?: number; sort?: SortOrder; }): Paginator // Reward history agent.rewardHistory(opts?: { limit?: number; sort?: SortOrder; }): Paginator ``` ### Withdrawal ```typescript // Partial withdrawal (with amount) or full withdrawal (without amount) agent.withdraw(amount?: string): Promise // Get current withdrawal status agent.status(): Promise // Poll until deactivation completes agent.waitForDeactivation(opts?: { interval?: number; // ms between polls. Default: 5000 timeout?: number; // ms before timeout. Default: 300000 onUpdate?: (status: WithdrawalStatusResponse) => void; }): Promise // Get fee info agent.fees(): Promise // Get withdrawal limit agent.limit(eoa: Address): Promise ``` ### Rewards ```typescript // Claim accumulated rewards agent.claimRewards(): Promise ``` ### Protocols ```typescript // Get agent's current protocols agent.protocols(): Promise // Update agent's protocol set agent.updateProtocols(protocols: string[]): Promise // Get agent's constraint configuration agent.constraints(): Promise // Update agent's constraints agent.updateConstraints(constraints: ConstraintConfig[]): Promise // Get whitelist info agent.whitelist(): Promise ``` ## Paginator Paginated methods return a `Paginator` that supports async iteration and direct page access. ### Async Iteration ```typescript const paginator = agent.transactions({ sort: 'date_desc' }); for await (const tx of paginator) { console.log(tx.action, tx.status); } ``` ### Get First N Items ```typescript const recent = await agent.transactions({ sort: 'date_desc' }).first(10); // recent: Transaction[] ``` ### Direct Page Access ```typescript const page = await agent.transactions().page(2, { limit: 25 }); // page: PaginatedResponse // page.items: Transaction[] // page.total: number // page.page: number // page.limit: number // page.hasMore: boolean ``` ## Optimizer ### optimize() Get optimal allocation recommendations. ```typescript const result = await giza.optimize({ token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', capital: '1000000000', currentAllocations: { aave: '600000000', compound: '400000000', }, protocols: ['aave', 'compound', 'moonwell', 'fluid'], constraints: [ { kind: 'min_protocols', params: { min_protocols: 2 } }, ], chain: Chain.BASE, // Optional, defaults to configured chain wallet: agentWallet, // Optional }); ``` #### OptimizeOptions ```typescript interface OptimizeOptions { chain?: Chain; token: Address; capital: string; currentAllocations: Record; protocols: string[]; constraints?: ConstraintConfig[]; wallet?: Address; } ``` #### OptimizeResponse ```typescript interface OptimizeResponse { optimization_result: { allocations: Array<{ protocol: string; allocation: string; apr: number; }>; total_costs: number; weighted_apr_initial: number; weighted_apr_final: number; apr_improvement: number; gas_estimate_usd?: number; break_even_days?: number; }; action_plan: ActionDetail[]; calldata: CalldataInfo[]; } ``` ## Types ### Enums ```typescript enum AgentStatus { UNKNOWN = 'unknown', ACTIVATING = 'activating', ACTIVATION_FAILED = 'activation_failed', ACTIVATED = 'activated', RUNNING = 'running', RUN_FAILED = 'run_failed', BLOCKED = 'blocked', DEACTIVATING = 'deactivating', DEACTIVATION_FAILED = 'deactivation_failed', DEACTIVATED = 'deactivated', EMERGENCY = 'emergency', DEACTIVATED_FEE_NOT_PAID = 'deactivated_fee_not_paid', BRIDGING = 'bridging', } enum TxAction { UNKNOWN = 'unknown', APPROVE = 'approve', DEPOSIT = 'deposit', TRANSFER = 'transfer', BRIDGE = 'bridge', WITHDRAW = 'withdraw', SWAP = 'swap', REFILL_GAS_TANK = 'refill_gas_tank', WRAP = 'wrap', UNWRAP = 'unwrap', FEE_TRANSFER = 'fee_transfer', } enum TxStatus { UNKNOWN = 'unknown', PENDING = 'pending', APPROVED = 'approved', CANCELLED = 'cancelled', FAILED = 'failed', } enum SortOrder { DATE_ASC = 'date_asc', DATE_DESC = 'date_desc', } enum Period { ALL = 'all', DAY = 'day', } enum ExecutionStatus { RUNNING = 'running', FAILED = 'failed', SUCCESS = 'success', } enum WalletConstraints { MIN_PROTOCOLS = 'min_protocols', MAX_ALLOCATION_AMOUNT_PER_PROTOCOL = 'max_allocation_amount_per_protocol', MAX_AMOUNT_PER_PROTOCOL = 'max_amount_per_protocol', MIN_AMOUNT = 'min_amount', EXCLUDE_PROTOCOL = 'exclude_protocol', MIN_ALLOCATION_AMOUNT_PER_PROTOCOL = 'min_allocation_amount_per_protocol', } ``` ### Constraint Configuration ```typescript interface ConstraintConfig { kind: WalletConstraints | string; params: Record; } // Examples: { kind: 'min_protocols', params: { min_protocols: 3 } } { kind: 'max_amount_per_protocol', params: { protocol: 'aave', max_ratio: 0.4 } } { kind: 'min_amount', params: { min_amount: '100000000' } } { kind: 'exclude_protocol', params: { protocol: 'compound' } } ``` ### PaginatedResponse ```typescript interface PaginatedResponse { items: T[]; total: number; page: number; limit: number; hasMore: boolean; } ``` ## Error Handling The SDK exports typed error classes. Use `instanceof` to handle them. ```typescript import { GizaError, GizaAPIError, ValidationError, TimeoutError, NetworkError, NotImplementedError, } from '@gizatech/agent-sdk'; try { await agent.activate({ ... }); } catch (error) { if (error instanceof ValidationError) { // Invalid input (bad address, missing field) console.error(error.message); } else if (error instanceof GizaAPIError) { // Server returned an error console.error(error.statusCode, error.message); if (error.statusCode === 401) { /* auth issue */ } if (error.statusCode === 429) { /* rate limited */ } } else if (error instanceof TimeoutError) { // Request timed out } else if (error instanceof NetworkError) { // Network connectivity issue } } ``` ### Error Hierarchy ``` GizaError (base) +-- ValidationError (input validation) +-- NotImplementedError (feature not available) +-- GizaAPIError (API returned error; has .statusCode, .message) +-- TimeoutError (request timeout) +-- NetworkError (connectivity failure) ``` ## Common Patterns ### Multi-Chain Setup ```typescript import { Giza, Chain } from '@gizatech/agent-sdk'; const chains = [Chain.BASE, Chain.ARBITRUM, Chain.ETHEREUM]; const clients = chains.map(chain => new Giza({ chain })); // Create agents on each chain const agents = await Promise.all( clients.map(c => c.createAgent(userWallet)) ); // Compare APRs const aprs = await Promise.all(agents.map(a => a.apr())); ``` ### Constraint-Based Activation ```typescript await agent.activate({ owner: userWallet, token: USDC, protocols: ['aave', 'compound', 'moonwell', 'fluid'], txHash: depositTxHash, constraints: [ { kind: 'min_protocols', params: { min_protocols: 3 } }, { kind: 'max_amount_per_protocol', params: { protocol: 'fluid', max_ratio: 0.3 }, }, { kind: 'min_amount', params: { min_amount: '100000000' } }, ], }); ``` ### Performance Dashboard ```typescript async function buildDashboard(agent: Agent) { const [info, aprData, perf] = await Promise.all([ agent.portfolio(), agent.apr(), agent.performance(), ]); const recent = await agent .transactions({ sort: 'date_desc' }) .first(10); return { status: info.status, currentAPR: aprData.apr, totalValue: perf.performance[perf.performance.length - 1]?.value_in_usd, protocols: info.selected_protocols, recentActivity: recent, }; } ``` ### Withdrawal Flow ```typescript // Partial: withdraw specific amount, agent stays active await agent.withdraw('500000000'); // Full: deactivate and withdraw everything await agent.withdraw(); const result = await agent.waitForDeactivation({ interval: 5000, timeout: 300000, onUpdate: (status) => console.log(status.status), }); ``` ### IaaS (Intelligence as a Service) Use the optimizer independently with your own execution infrastructure. ```typescript const giza = new Giza({ chain: Chain.BASE }); const result = await giza.optimize({ token: USDC, capital: '1000000000', currentAllocations: { aave: '600000000', compound: '400000000' }, protocols: ['aave', 'compound', 'moonwell'], constraints: [ { kind: 'min_protocols', params: { min_protocols: 2 } }, ], }); if (result.optimization_result.apr_improvement > 0.5) { // Execute with your own infrastructure for (const call of result.calldata) { await yourSmartAccount.execute({ to: call.contract_address, data: encode(call.function_name, call.parameters), }); } } ``` ### Iterating Paginated Results ```typescript // Async iteration (fetches pages automatically) for await (const tx of agent.transactions()) { console.log(tx.action, tx.status); } // Get first N items const top5 = await agent.transactions({ sort: 'date_desc' }).first(5); // Access specific page const page3 = await agent.transactions().page(3, { limit: 25 }); console.log(`Page ${page3.page} of ${Math.ceil(page3.total / page3.limit)}`); console.log(`Items: ${page3.items.length}, Has more: ${page3.hasMore}`); ``` ### Retry Pattern ```typescript import { GizaAPIError } from '@gizatech/agent-sdk'; async function withRetry( fn: () => Promise, maxRetries = 3 ): Promise { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (i === maxRetries - 1) throw error; if (error instanceof GizaAPIError && error.statusCode >= 500) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else { throw error; } } } throw new Error('Unreachable'); } ``` ### Transaction Analysis ```typescript import { TxAction, TxStatus } from '@gizatech/agent-sdk'; const txs = await agent .transactions({ sort: 'date_desc' }) .first(100); const byAction = txs.reduce((acc, tx) => { acc[tx.action] = (acc[tx.action] || 0) + 1; return acc; }, {} as Record); const failedCount = txs.filter( tx => tx.status === TxStatus.FAILED ).length; ``` ### React Query Integration ```typescript import { useQuery } from '@tanstack/react-query'; function useAgentAPR(agent: Agent) { return useQuery({ queryKey: ['apr', agent.wallet], queryFn: () => agent.apr(), staleTime: 60_000, refetchInterval: 60_000, }); } function useAgentPortfolio(agent: Agent) { return useQuery({ queryKey: ['portfolio', agent.wallet], queryFn: () => agent.portfolio(), staleTime: 30_000, refetchInterval: 30_000, }); } ```