Skip to main content

Overview

This guide will get you up and running with the Giza Agent SDK. You’ll create a smart account, activate an agent, and start optimizing yield automatically.
This quickstart focuses on the Agentic integration. For IaaS (Intelligence as a Service) using the Optimizer only, see the IaaS Integration Guide.

Architecture

Prerequisites

Check your version: node --versionDownload from nodejs.org if needed.
The SDK is built for TypeScript. JavaScript works too, but you’ll miss out on type safety.
You’ll need:
  • GIZA_API_KEY - Your partner API key
  • GIZA_API_URL - Giza backend URL
  • GIZA_PARTNER_NAME - Your partner identifier

Get API Keys

Contact Giza to obtain your credentials

Installation

npm install @giza/agent-sdk

Environment Setup

Create a .env file in your project root:
.env
GIZA_API_KEY=...
GIZA_API_URL=...
GIZA_PARTNER_NAME=...
Never commit your .env file to version control! Add it to .gitignore.

Complete Integration Flow

Step 1: Initialize the SDK

import { GizaAgent, Chain } from '@giza/agent-sdk';

// Initialize once, reuse throughout your app
const giza = new GizaAgent({
  chainId: Chain.BASE,
  timeout: 60000,      // Optional: 60s timeout
  enableRetry: true,   // Optional: retry failed requests
});

Step 2: Create a Smart Account

Generate a smart account for your user. This is where they’ll deposit funds.
async function onboardUser(userWallet: string) {
  const account = await giza.agent.createSmartAccount({
    origin_wallet: userWallet as `0x${string}`,
  });

  console.log('Smart Account:', account.smartAccountAddress);
  console.log('Deposit funds to this address');
  
  return account;
}
The smart account address is deterministic - calling createSmartAccount with the same origin_wallet always returns the same address.

Step 3: Get Available Protocols

Check which DeFi protocols are available for the token you want to optimize:
const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';

const { protocols } = await giza.agent.getProtocols(USDC_BASE);

console.log('Available protocols:', protocols);
// ['aave', 'compound', 'moonwell', 'fluid', ...]

Step 4: User Deposits Funds

1

User sends tokens to smart account

User transfers USDC (or supported token) to the smartAccountAddress from Step 2.
2

Wait for confirmation

Wait for the transaction to be confirmed on-chain.
// Example: User deposits via your UI
const depositTxHash = await userWallet.sendTransaction({
  to: account.smartAccountAddress,
  value: parseUnits('1000', 6), // 1000 USDC (6 decimals)
});

Step 5: Activate the Agent

After the user deposits, activate the agent to start optimization:
const activation = await giza.agent.activate({
  wallet: account.smartAccountAddress,
  origin_wallet: userWallet,
  initial_token: USDC_BASE,
  selected_protocols: ['aave', 'compound', 'moonwell'],
  tx_hash: depositTxHash, // Optional but recommended
  constraints: [
    {
      kind: 'min_protocols',
      params: { min_protocols: 2 } // Always diversify
    }
  ]
});

console.log(activation.message);
Once activated, the agent automatically:
  • Monitors APRs across selected protocols
  • Rebalances capital for optimal yield
  • Handles all gas costs internally
  • Continues optimizing until deactivated

Step 6: Monitor Performance

Track the agent’s performance:
// Get current portfolio status
const portfolio = await giza.agent.getPortfolio({
  wallet: account.smartAccountAddress,
});

console.log('Status:', portfolio.status);
console.log('Protocols:', portfolio.selected_protocols);

// Get APR
const { apr } = await giza.agent.getAPR({
  wallet: account.smartAccountAddress,
});

console.log(`Current APR: ${apr.toFixed(2)}%`);

// Get performance history
const performance = await giza.agent.getPerformance({
  wallet: account.smartAccountAddress,
});

performance.performance.forEach(point => {
  console.log(`${point.date}: $${point.value_in_usd}`);
});

Step 7: Withdraw Funds

Users can withdraw partially or fully at any time:
// Withdraw everything and deactivate agent
await giza.agent.withdraw({
  wallet: account.smartAccountAddress,
  transfer: true, // Transfer to origin wallet
});

// Poll for completion
const finalStatus = await giza.agent.pollWithdrawalStatus(
  account.smartAccountAddress,
  {
    interval: 5000,
    timeout: 300000,
    onUpdate: (status) => console.log('Status:', status),
  }
);

console.log('Withdrawal complete:', finalStatus.status);

Additional Operations

Top-Up Active Agent

await giza.agent.topUp({
  wallet: smartAccountAddress,
  tx_hash: newDepositTxHash,
});

Update Protocols

await giza.agent.updateProtocols(
  smartAccountAddress,
  ['aave', 'compound', 'moonwell', 'fluid']
);

Manual Rebalance

const result = await giza.agent.run({
  wallet: smartAccountAddress
});

Error Handling

Always wrap SDK calls in try-catch blocks:
import { ValidationError, GizaAPIError, TimeoutError } from '@giza/agent-sdk';

try {
  const account = await giza.agent.createSmartAccount({
    origin_wallet: userWallet,
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Invalid input:', error.message);
  } else if (error instanceof GizaAPIError) {
    console.error('API error:', error.statusCode, error.message);
  } else if (error instanceof TimeoutError) {
    console.error('Request timed out');
  }
}

Error Handling Guide

Learn about error types and handling strategies

Troubleshooting

Make sure:
  • .env file exists in project root
  • You’re loading it (e.g., dotenv package)
  • Variable names match exactly: GIZA_API_KEY, GIZA_API_URL, GIZA_PARTNER_NAME
Addresses must:
  • Start with 0x
  • Be 42 characters long (0x + 40 hex chars)
  • Use valid hex characters (0-9, a-f, A-F)
Check:
  • API key is correct and active
  • Partner name matches your registration
  • API URL is correct
Ensure:
  • Smart account has received the deposit
  • Transaction hash is valid and confirmed
  • Selected protocols are available for the token
  • Token address is correct for the chain

Full Troubleshooting Guide

See common issues and solutions

Next Steps