# Use Giza with AI Agents
Source: https://docs.gizatech.xyz/ai-agents/setup
Manage your Giza Agent by chatting with an AI assistant
Talk to an AI assistant to manage your Giza Agent using natural language. Deposit, withdraw, check your portfolio, switch strategies, and more -- just by asking.
## What You Can Do
* Check your portfolio and current yield
* Deposit and withdraw funds
* View your rewards and claim them
* Change your strategy and selected markets
* See your transaction history
* Get help setting up a new account
## Setup
Pick the AI client you want to use and follow the steps below.
Launch the Claude Desktop app on your computer.
Click the gear icon to open **Settings**, then click **Customize**.
Click **Connectors** in the sidebar, then click **Add marketplace**. Enter the following URL and click **Sync**:
```
https://github.com/gizatechxyz/giza-hub
```
Go to **Skills** in the sidebar. You'll see "Giza skills" available. Click **Install**.
Open a new chat and ask anything -- for example, "How's my portfolio?" or "Help me get started."
You can also type `/giza` in the chat to invoke the skill directly.
If you haven't already, install Claude Code from [claude.com/claude-code](https://claude.com/claude-code).
Run the following command:
```bash theme={null}
/plugin marketplace add gizatechxyz/giza-hub
```
```bash theme={null}
/plugin install giza-skills
```
Ask Giza questions directly in your Claude Code session.
```bash theme={null}
npm i -g openclaw
```
```bash theme={null}
npx clawhub@latest install giza
```
Open Openclaw and start asking Giza questions.
## First Time Login
On your first interaction, the AI will send you a login link. Open it in your browser to connect your wallet. After that, you're set -- future sessions will remember you.
## Example Prompts
Here are a few things you can ask:
* "Help me get started with Giza"
* "How's my portfolio doing?"
* "What's my current yield?"
* "Withdraw \$100"
* "What rewards have I earned?"
* "What protocols am I using?"
# Activate Wallet
Source: https://docs.gizatech.xyz/api-reference/agents/activate-wallet
POST /api/v1/{chain_id}/wallets
Activate a new wallet for an agent
**SDK Alternative**: Use `agent.activate(options)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/lifecycle)
## Description
Activates a new wallet for an agent. This endpoint must be called after the user has deposited funds to their smart account.
## Request Body
The smart account wallet address
The user's externally owned account (origin wallet)
The token address that was deposited (e.g., USDC)
List of protocol names to use for optimization
Transaction hash of the initial deposit (recommended)
Optional constraints for the agent
**Constraint types:**
* `min_protocols` - Minimum number of protocols to use
* `max_allocation_amount_per_protocol` - Maximum amount per protocol
* `exclude_protocol` - Protocols to exclude
## Example Request
```bash theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"wallet": "0x1234567890abcdef1234567890abcdef12345678",
"eoa": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
"initial_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"selected_protocols": ["aave", "compound", "moonwell"],
"tx_hash": "0x...",
"constraints": [
{
"kind": "min_protocols",
"params": { "min_protocols": 2 }
}
]
}'
```
## Response
Confirmation message
The wallet address that was activated
```json Response Example theme={null}
{
"message": "Agent activated successfully",
"wallet": "0x1234567890abcdef1234567890abcdef12345678"
}
```
## Error Responses
| Status | Description |
| ------ | ---------------------------------- |
| `400` | Invalid input data |
| `403` | Access denied or deposit too large |
| `422` | Validation error |
| `500` | Internal server error |
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"wallet": "0x1234567890abcdef1234567890abcdef12345678",
"eoa": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
"initial_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"selected_protocols": ["aave", "compound", "moonwell"]
}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify({
wallet: '0x1234567890abcdef1234567890abcdef12345678',
eoa: '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
initial_token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
selected_protocols: ['aave', 'compound', 'moonwell'],
}),
}
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.post(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets',
headers={
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
json={
'wallet': '0x1234567890abcdef1234567890abcdef12345678',
'eoa': '0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',
'initial_token': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
'selected_protocols': ['aave', 'compound', 'moonwell'],
}
)
data = response.json()
```
```json 201 Created theme={null}
{
"message": "Agent activated successfully",
"wallet": "0x1234567890abcdef1234567890abcdef12345678"
}
```
```json 400 Bad Request theme={null}
{
"detail": "Invalid input data"
}
```
```json 403 Forbidden theme={null}
{
"detail": "Access denied or deposit is too large"
}
```
# Claim Rewards
Source: https://docs.gizatech.xyz/api-reference/agents/claim-rewards
POST /api/v1/{chain_id}/wallets/{wallet}:claim-rewards
Claim accrued rewards for a wallet
**SDK Alternative**: Use `agent.claimRewards()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/rewards)
## Description
Claims accrued rewards (such as protocol incentives) for a specific wallet. Rewards are transferred to the smart account.
## Path Parameters
The blockchain chain ID
The wallet address
## Response
List of claimed rewards
Token address of the reward
Amount in smallest token units
Amount as a decimal
Current price in underlying token
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:claim-rewards" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:claim-rewards',
{
method: 'POST',
headers: {
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
}
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"rewards": [
{
"token": "0x...",
"amount": 1000000000000000000,
"amount_float": 1.0,
"current_price_in_underlying": 50.0
}
]
}
```
# Create Smart Account
Source: https://docs.gizatech.xyz/api-reference/agents/create-smart-account
POST /api/v1/proxy/zerodev/smart-accounts
Create a new smart account for a user
**SDK Alternative**: Use `giza.createAgent(eoa)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/giza)
## Description
Creates a new ZeroDev smart account for a user's externally owned account (EOA). The smart account address is **deterministic** — calling this endpoint with the same EOA and chain always returns the same address, so it is safe to call multiple times.
This is the first step in the agentic integration flow. After creating the smart account, the user deposits funds to the returned address, then you activate the agent.
## Request Body
The user's externally owned account (wallet) address.
Must be a valid Ethereum address (0x + 40 hex characters).
Chain ID for the smart account.
Supported values: `1` (Ethereum), `137` (Polygon), `8453` (Base), `42161` (Arbitrum), `84532` (Base Sepolia), `11155111` (Sepolia)
Agent identifier. Defaults to `giza-app`.
## Example Request
```bash theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"eoa": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"chain": 8453,
"agent_id": "giza-app"
}'
```
## Response
The created smart account address. This is where the user should deposit funds.
The Giza backend wallet that will hold session keys for agent operations.
```json Response Example theme={null}
{
"smartAccount": "0xAbC1234567890aBcDeF1234567890AbCdEf123456",
"backendWallet": "0xDeF9876543210FeDcBa9876543210FeDcBa987654"
}
```
## Error Responses
| Status | Description |
| ------ | ----------------------------------------- |
| `400` | Invalid input data |
| `401` | Unauthorized - invalid API key |
| `422` | Validation error (invalid address format) |
| `500` | Internal server error |
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"eoa": "0x742d35Cc6634C0532925a3b844Bc454e4438f44e",
"chain": 8453,
"agent_id": "giza-app"
}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify({
eoa: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
chain: 8453,
agent_id: 'giza-app',
}),
}
);
const data = await response.json();
console.log('Smart Account:', data.smartAccount);
```
```python Python theme={null}
import requests
response = requests.post(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts',
headers={
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
json={
'eoa': '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
'chain': 8453,
'agent_id': 'giza-app',
}
)
data = response.json()
print('Smart Account:', data['smartAccount'])
```
```json 200 OK theme={null}
{
"smartAccount": "0xAbC1234567890aBcDeF1234567890AbCdEf123456",
"backendWallet": "0xDeF9876543210FeDcBa9876543210FeDcBa987654"
}
```
```json 400 Bad Request theme={null}
{
"detail": "Invalid input data"
}
```
```json 422 Validation Error theme={null}
{
"detail": [
{
"loc": ["body", "eoa"],
"msg": "Invalid Ethereum address",
"type": "value_error"
}
]
}
```
# Deactivate Wallet
Source: https://docs.gizatech.xyz/api-reference/agents/deactivate-wallet
POST /api/v1/{chain_id}/wallets/{wallet}:deactivate
Deactivate an agent and optionally withdraw funds
**SDK Alternative**: Use `agent.deactivate()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/lifecycle)
## Description
Deactivates the agent for a specific wallet. This stops automatic rebalancing and optionally transfers remaining funds to the origin wallet.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
Whether to transfer remaining balance to the origin wallet
## Response
Returns `201 Created` on success.
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:deactivate?transfer=true" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:deactivate?transfer=true',
{
method: 'POST',
headers: {
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
}
);
```
```json 201 Created theme={null}
{
"message": "Wallet deactivation triggered"
}
```
```json 403 Forbidden theme={null}
{
"detail": "Wallet is not active"
}
```
# Get Wallet APR
Source: https://docs.gizatech.xyz/api-reference/agents/get-apr
GET /api/v1/{chain_id}/wallets/{wallet}/apr
Get the APR for a wallet
**SDK Alternative**: Use `agent.apr(options?)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/monitoring)
## Description
Retrieves the Annual Percentage Rate (APR) for a wallet based on its historical performance.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
ISO datetime to start APR calculation (e.g., `2025-05-06T01:00:00+02:00`)
Optional end date for APR calculation
If `true`, use end\_date as the exact last performance point
## Response
Annual Percentage Rate as a decimal (e.g., 5.5 = 5.5%)
Optional breakdown by sub-periods
Period start date
Period end date
Return for the period
Initial value at period start
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../apr?start_date=2024-01-01T00:00:00Z"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../apr?start_date=2024-01-01T00:00:00Z'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"apr": 5.5,
"sub_periods": [
{
"start_date": "2024-01-01T00:00:00Z",
"end_date": "2024-01-15T00:00:00Z",
"return_": 0.02,
"initial_value": 1000.0
}
]
}
```
```json 400 Bad Request theme={null}
{
"detail": "Not enough historical data for APR calculation"
}
```
# Get Fee
Source: https://docs.gizatech.xyz/api-reference/agents/get-fee
GET /api/v1/{chain_id}/wallets/{wallet}/fee
Get fee information for a wallet
**SDK Alternative**: Use `agent.fees()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/withdrawals)
## Description
Retrieves the fee information for a wallet, including the percentage fee applied to yields.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
Optional amount to calculate fee for
## Response
Fee percentage (e.g., 0.1 = 10%)
Calculated fee amount (if amount was provided)
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../fee"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../fee'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"percentage_fee": 0.1,
"fee": 0
}
```
# Get Limit
Source: https://docs.gizatech.xyz/api-reference/agents/get-limit
GET /api/v1/{chain_id}/wallets/{wallet}/limit
Get deposit limit for a wallet
**SDK Alternative**: Use `agent.limit(eoa)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/withdrawals)
## Description
Retrieves the deposit limit and current balance for a wallet.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
The origin wallet (EOA) address
## Response
Maximum deposit limit
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../limit?eoa=0xabc..."
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../limit?eoa=0xabc...'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"limit": 100000
}
```
# Get Performance
Source: https://docs.gizatech.xyz/api-reference/agents/get-performance
GET /api/v1/{chain_id}/wallets/{wallet}/performance
Get performance chart data for a wallet
**SDK Alternative**: Use `agent.performance()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/monitoring)
## Description
Retrieves historical performance data for a wallet, including portfolio values and rewards over time.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
Start date for performance data (format: `YYYY-MM-DD HH:MM:SS`)
## Response
Array of performance data points
ISO date timestamp
Portfolio value in token units
Portfolio value in USD
Distribution of tokens in portfolio
Accrued rewards by token
Protocol allocations
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../performance?from_date=2024-01-01%2000:00:00"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../performance?from_date=2024-01-01 00:00:00'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"performance": [
{
"date": "2024-01-15T00:00:00Z",
"value": 1000.50,
"value_in_usd": 1000.50,
"token_distribution": {
"USDC": 1000.50
},
"accrued_rewards": {
"AAVE": {
"locked": 0.5,
"unlocked": 0.2,
"locked_value": 50.0,
"locked_value_usd": 50.0,
"unlocked_value": 20.0,
"unlocked_value_usd": 20.0
}
},
"portfolio": {
"aave": {
"value": 500.25,
"value_in_usd": 500.25
},
"compound": {
"value": 500.25,
"value_in_usd": 500.25
}
}
}
]
}
```
# Get Smart Account
Source: https://docs.gizatech.xyz/api-reference/agents/get-smart-account
GET /api/v1/proxy/zerodev/smart-accounts
Look up an existing smart account by EOA
**SDK Alternative**: Use `giza.getAgent(eoa)` or `giza.getSmartAccount(eoa)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/giza)
## Description
Looks up an existing smart account for a given EOA and chain. Returns the smart account address and backend wallet. Use this to retrieve a previously created smart account without creating a new one.
## Query Parameters
The user's externally owned account (wallet) address.
Chain ID to look up the smart account on.
Supported values: `1` (Ethereum), `137` (Polygon), `8453` (Base), `42161` (Arbitrum), `84532` (Base Sepolia), `11155111` (Sepolia)
Agent identifier. Defaults to `giza-app`.
## Example Request
```bash theme={null}
curl -X GET "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts?eoa=0x742d35Cc6634C0532925a3b844Bc454e4438f44e&chain=8453&agent_id=giza-app" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
## Response
The smart account address.
The Giza backend wallet associated with this smart account.
```json Response Example theme={null}
{
"smartAccount": "0xAbC1234567890aBcDeF1234567890AbCdEf123456",
"backendWallet": "0xDeF9876543210FeDcBa9876543210FeDcBa987654"
}
```
## Error Responses
| Status | Description |
| ------ | ---------------------------------------------- |
| `401` | Unauthorized - invalid API key |
| `404` | Smart account not found for this EOA and chain |
| `422` | Validation error (invalid address format) |
| `500` | Internal server error |
```bash cURL theme={null}
curl -X GET "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts?eoa=0x742d35Cc6634C0532925a3b844Bc454e4438f44e&chain=8453&agent_id=giza-app" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
```javascript JavaScript theme={null}
const params = new URLSearchParams({
eoa: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
chain: '8453',
agent_id: 'giza-app',
});
const response = await fetch(
`https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts?${params}`,
{
headers: {
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
}
);
const data = await response.json();
console.log('Smart Account:', data.smartAccount);
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/proxy/zerodev/smart-accounts',
headers={
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
params={
'eoa': '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
'chain': 8453,
'agent_id': 'giza-app',
}
)
data = response.json()
print('Smart Account:', data['smartAccount'])
```
```json 200 OK theme={null}
{
"smartAccount": "0xAbC1234567890aBcDeF1234567890AbCdEf123456",
"backendWallet": "0xDeF9876543210FeDcBa9876543210FeDcBa987654"
}
```
```json 404 Not Found theme={null}
{
"detail": "Smart account not found"
}
```
# Get Transaction History
Source: https://docs.gizatech.xyz/api-reference/agents/get-transactions
GET /api/v1/{chain_id}/wallets/{wallet}/transactions
Get transaction history for a wallet
**SDK Alternative**: Use `agent.transactions()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/transactions)
## Description
Retrieves paginated transaction history for a wallet including deposits, withdrawals, swaps, and rebalancing operations.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
Page number (starts at 1)
Number of items per page (max 100)
Sort order: `date_desc` or `date_asc`
## Response
Array of transactions
Transaction type: `deposit`, `withdraw`, `swap`, `transfer`, `bridge`, `approve`
ISO timestamp
Transaction amount
Token address
Status: `pending`, `approved`, `cancelled`, `failed`
Blockchain transaction hash
Associated protocol (if applicable)
Pagination info
Total number of transactions
Total number of pages
Current page number
Items per page
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../transactions?page=1&limit=20&sort=date_desc"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../transactions?page=1&limit=20'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"transactions": [
{
"action": "deposit",
"date": "2024-01-15T10:30:00Z",
"amount": 1000000000,
"token_type": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"status": "approved",
"transaction_hash": "0xabc...",
"protocol": "aave"
},
{
"action": "swap",
"date": "2024-01-16T08:00:00Z",
"amount": 500000000,
"token_type": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"status": "approved",
"transaction_hash": "0xdef...",
"protocol": "compound",
"new_token": "0x..."
}
],
"pagination": {
"total_items": 15,
"total_pages": 1,
"current_page": 1,
"items_per_page": 20
}
}
```
# Get Wallet Deposits
Source: https://docs.gizatech.xyz/api-reference/agents/get-wallet-deposits
GET /api/v1/{chain_id}/wallets/{wallet}/deposits
Get deposit information for a wallet
**SDK Alternative**: Use `agent.deposits()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/monitoring)
## Description
Retrieves the list of deposits made to a specific wallet.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
If `true`, treats wallet as an EOA address
## Response
List of deposits
Deposit amount in smallest token unit
Token address
ISO date of deposit
Transaction hash
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../deposits"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../deposits'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"deposits": [
{
"amount": 1000000000,
"token_type": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"date": "2024-01-15T10:30:00Z",
"tx_hash": "0xabc123..."
},
{
"amount": 500000000,
"token_type": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"date": "2024-01-20T14:00:00Z",
"tx_hash": "0xdef456..."
}
]
}
```
# Get Wallet Information
Source: https://docs.gizatech.xyz/api-reference/agents/get-wallet-info
GET /api/v1/{chain_id}/wallets/{wallet}
Get information about a specific wallet
**SDK Alternative**: Use `agent.portfolio()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/monitoring)
## Description
Retrieves detailed information about a specific wallet including status, deposits, withdrawals, and protocol allocations.
## Path Parameters
The blockchain chain ID (e.g., 8453 for Base)
The wallet address to query
## Query Parameters
If `true`, treats the wallet parameter as an EOA (origin wallet) address and looks up the associated smart account
## Response
The wallet address
Current agent status: `activated`, `activating`, `deactivating`, `deactivated`, `running`, `blocked`, `emergency`
List of deposits made to the wallet
Deposit amount in smallest token unit
Token address
ISO date of deposit
Transaction hash
List of withdrawals
Protocols the agent is configured to use
Currently active protocol (if single protocol mode)
Currently active protocols (if multi protocol mode)
ISO date when the agent was activated
ISO date of last deactivation (if applicable)
The origin wallet address
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x1234567890abcdef1234567890abcdef12345678"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x1234567890abcdef1234567890abcdef12345678'
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x1234567890abcdef1234567890abcdef12345678'
)
data = response.json()
```
```json 200 OK theme={null}
{
"wallet": "0x1234567890abcdef1234567890abcdef12345678",
"status": "activated",
"deposits": [
{
"amount": 1000000000,
"token_type": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"date": "2024-01-15T10:30:00Z",
"tx_hash": "0xabc..."
}
],
"withdraws": [],
"selected_protocols": ["aave", "compound", "moonwell"],
"current_protocols": ["aave"],
"current_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"activation_date": "2024-01-15T10:35:00Z",
"last_deactivation_date": null,
"last_reactivation_date": null,
"eoa": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
}
```
```json 404 Not Found theme={null}
{
"detail": "Data not found for the wallet"
}
```
# Run Agent
Source: https://docs.gizatech.xyz/api-reference/agents/run-agent
POST /api/v1/{chain_id}/wallets/{wallet}:run
Manually trigger an agent run
**SDK Alternative**: Use `agent.run()` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/lifecycle)
## Description
Manually triggers an optimization run for a specific wallet. The agent will analyze current APRs and rebalance if beneficial.
Agents automatically run periodically. Use this endpoint only when you need to force an immediate optimization.
## Path Parameters
The blockchain chain ID
The wallet address
## Response
Run status: `completed`, `no_action`, `failed`
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:run" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:run',
{
method: 'POST',
headers: {
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
}
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"status": "completed"
}
```
```json 200 OK (No Action Needed) theme={null}
{
"status": "no_action"
}
```
# Top Up
Source: https://docs.gizatech.xyz/api-reference/agents/top-up
POST /api/v1/{chain_id}/wallets/{wallet}:top-up
Add funds to an active agent
**SDK Alternative**: Use `agent.topUp(txHash)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/lifecycle)
## Description
Adds additional funds to an already active agent. The agent will include the new funds in its optimization strategy.
## Path Parameters
The blockchain chain ID
The wallet address
## Query Parameters
Transaction hash of the deposit
## Response
Returns `201 Created` on success.
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:top-up?tx_hash=0xabc123..." \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:top-up?tx_hash=0xabc123...',
{
method: 'POST',
headers: {
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
}
);
```
```json 201 Created theme={null}
{
"message": "Top-up process started"
}
```
```json 403 Forbidden theme={null}
{
"detail": "Wallet is not active"
}
```
# Update Protocols
Source: https://docs.gizatech.xyz/api-reference/agents/update-protocols
PUT /api/v1/{chain_id}/wallets/{wallet}/protocols
Update the selected protocols for a wallet
**SDK Alternative**: Use `agent.updateProtocols(protocols)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/protocols)
## Description
Updates the list of protocols that the agent can use for optimization. The agent will rebalance according to the new protocol selection.
## Path Parameters
The blockchain chain ID
The wallet address
## Request Body
The request body should be a JSON array of protocol names:
```json theme={null}
["aave", "compound", "moonwell", "fluid"]
```
## Response
Returns `204 No Content` on success.
```bash cURL theme={null}
curl -X PUT "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../protocols" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '["aave", "compound", "moonwell", "fluid"]'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x.../protocols',
{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify(['aave', 'compound', 'moonwell', 'fluid']),
}
);
```
```text 204 No Content theme={null}
(empty response body)
```
```json 400 Bad Request theme={null}
{
"detail": "Invalid protocol name"
}
```
# Withdraw
Source: https://docs.gizatech.xyz/api-reference/agents/withdraw
POST /api/v1/{chain_id}/wallets/{wallet}:withdraw
Execute a partial withdrawal from a wallet
**SDK Alternative**: Use `agent.withdraw(amount?)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/agent/withdrawals)
## Description
Executes a partial withdrawal from a wallet. The agent remains active after a partial withdrawal.
For full withdrawal (deactivation), use the [Deactivate Wallet](/api-reference/agents/deactivate-wallet) endpoint.
## Path Parameters
The blockchain chain ID
The wallet address
## Request Body
Amount to withdraw in smallest token units (e.g., 1000000 = 1 USDC)
## Response
Withdrawal date
Total withdrawn value
Total withdrawn value in USD
Breakdown of withdrawn tokens
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:withdraw" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{"amount": 500000000}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets/0x...:withdraw',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify({ amount: 500000000 }),
}
);
```
```json 200 OK theme={null}
{
"date": "2024-01-20T15:00:00Z",
"total_value": 500.0,
"total_value_in_usd": 500.0,
"withdraw_details": [
{
"token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"amount": "500000000",
"value": 500.0,
"value_in_usd": 500.0,
"principal_amount": 490000000,
"yield_amount": 10000000,
"fee_amount": 0
}
]
}
```
# Authentication
Source: https://docs.gizatech.xyz/api-reference/authentication
How to authenticate with the Giza API
## Overview
The Giza API uses API key authentication. Authenticated endpoints require two headers on each request.
## Required Headers
```bash theme={null}
X-Partner-API-Key: your-api-key
X-Partner-Name: your-partner-name
```
### Example Request
```bash theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/wallets" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"wallet": "0x1234567890abcdef1234567890abcdef12345678",
"eoa": "0xabcdefabcdefabcdefabcdefabcdefabcdefabcd",
"initial_token": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"selected_protocols": ["aave", "compound", "moonwell"]
}'
```
## Obtaining API Credentials
Reach out to the Giza team to request partner access.
Visit gizatech.xyz to get started
You'll receive:
* **API Key**: A unique key for authentication
* **Partner Name**: Your registered partner identifier
* **Backend URL**: The API endpoint URL
Store credentials securely as environment variables:
```bash .env theme={null}
GIZA_API_KEY=your-api-key
GIZA_PARTNER_NAME=your-partner-name
GIZA_API_URL=https://partners-backend-1038109371738.europe-west1.run.app
```
## Authentication Scopes
Different endpoints require different authentication levels:
### Public Endpoints (No Auth Required)
These endpoints can be called without authentication:
| Endpoint | Description |
| ------------------------------------------ | ---------------------------------- |
| `GET /api/v1/healthcheck` | Health check |
| `GET /api/v1/chains` | List supported chains |
| `GET /api/v1/{chain_id}/tokens` | List supported tokens |
| `GET /api/v1/{chain_id}/{token}/protocols` | Get protocol information |
| `GET /api/v1/{chain_id}/wallets/{wallet}` | Get wallet information (read-only) |
| `GET /api/v1/{chain_id}/stats` | Get statistics |
### Authenticated Endpoints
These endpoints require API key authentication:
| Endpoint | Description |
| -------------------------------------------------------- | ------------------- |
| `POST /api/v1/{chain_id}/wallets` | Activate wallet |
| `POST /api/v1/{chain_id}/wallets/{wallet}:deactivate` | Deactivate wallet |
| `POST /api/v1/{chain_id}/wallets/{wallet}:withdraw` | Withdraw funds |
| `POST /api/v1/{chain_id}/wallets/{wallet}:run` | Trigger agent run |
| `POST /api/v1/{chain_id}/wallets/{wallet}:top-up` | Top up wallet |
| `POST /api/v1/{chain_id}/wallets/{wallet}:claim-rewards` | Claim rewards |
| `PUT /api/v1/{chain_id}/wallets/{wallet}/protocols` | Update protocols |
| `POST /api/v1/optimizer/{chain_id}/optimize` | Optimize allocation |
## Error Responses
### Invalid or Missing API Key
```json theme={null}
{
"detail": "Invalid or missing API key"
}
```
**HTTP Status**: `401 Unauthorized`
### Access Denied
```json theme={null}
{
"detail": "Access denied"
}
```
**HTTP Status**: `403 Forbidden`
This occurs when:
* Trying to access another partner's wallet
* API key is inactive
* Partner doesn't have permission for the operation
## Security Best Practices
**Never expose your API key in client-side code!** Always make API calls from your backend server.
* Use environment variables, not hardcoded strings
* Never commit `.env` files to version control
* Use a secrets manager in production (AWS Secrets Manager, HashiCorp Vault, etc.)
Contact Giza to regenerate your API key if:
* You suspect it's been compromised
* An employee with access leaves your organization
* As part of regular security hygiene
Always use HTTPS when making API requests. Never send API keys over unencrypted connections.
Make all authenticated API calls from your backend:
```typescript theme={null}
// ✅ Good: Server-side API call
// pages/api/activate.ts (Next.js)
export default async function handler(req, res) {
const response = await fetch('https://api.giza.../wallets', {
headers: {
'X-Partner-API-Key': process.env.GIZA_API_KEY,
'X-Partner-Name': process.env.GIZA_PARTNER_NAME,
},
body: req.body,
});
res.json(await response.json());
}
// ❌ Bad: Client-side API call (exposes key!)
// Don't do this in frontend code
fetch('https://api.giza.../wallets', {
headers: {
'X-Partner-API-Key': 'exposed-key', // NEVER DO THIS
},
});
```
## Using with the SDK
The [TypeScript SDK](/sdk-reference/overview) handles authentication automatically:
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
// SDK reads from environment variables:
// - GIZA_API_KEY
// - GIZA_PARTNER_NAME
// - GIZA_API_URL
const giza = new Giza({
chain: Chain.BASE,
});
// Authentication headers are added automatically
const agent = await giza.createAgent('0x...');
await agent.activate({...});
```
We recommend using the SDK for simplified authentication
## Next Steps
Create your first agent
Discover available protocols
# API Introduction
Source: https://docs.gizatech.xyz/api-reference/introduction
HTTP API for Giza Agent services
## Overview
The Giza API is the HTTP layer behind the [SDK](/sdk-reference/overview). It gives direct access to all agent services.
**For most use cases, the [TypeScript SDK](/sdk-reference/overview)** is easier -- it gives you type safety, automatic authentication, and structured error handling. Use the HTTP API directly when:
* Building in a language without SDK support
* Needing lower-level control
* Integrating with existing HTTP infrastructure
## Base URL
```
https://partners-backend-1038109371738.europe-west1.run.app
```
## API Groups
Core agent operations: activation, monitoring, withdrawals
DeFi protocol information and availability
Capital allocation optimization
Platform-wide statistics and TVL
Reward staking status and history
Supported chains and tokens
## Common Parameters
### Chain ID
Most endpoints require a `chain_id` path parameter:
| Chain | ID |
| ------------ | ---------- |
| Base | `8453` |
| Ethereum | `1` |
| Arbitrum | `42161` |
| Polygon | `137` |
| Base Sepolia | `84532` |
| Sepolia | `11155111` |
### Wallet Address
Wallet addresses must be valid Ethereum addresses:
* Start with `0x`
* 42 characters total (0x + 40 hex characters)
* Case-insensitive
## Response Format
All successful responses return JSON with the following structure:
```json theme={null}
{
"data": { ... }
}
```
Error responses follow this format:
```json theme={null}
{
"detail": [
{
"loc": ["path", "wallet"],
"msg": "Invalid wallet address",
"type": "value_error"
}
]
}
```
## HTTP Status Codes
| Code | Description |
| ----- | ------------------------------------------ |
| `200` | Success |
| `201` | Created |
| `204` | No Content (success with no response body) |
| `400` | Bad Request - Invalid parameters |
| `401` | Unauthorized - Invalid API key |
| `403` | Forbidden - Access denied |
| `404` | Not Found - Resource doesn't exist |
| `422` | Validation Error - Invalid input |
| `500` | Internal Server Error |
| `503` | Service Unavailable |
## Rate Limits
API requests are rate-limited per partner. If you exceed limits, you'll receive a `429 Too Many Requests` response.
Contact Giza to discuss rate limit increases for production use cases.
## OpenAPI Specification
The complete API specification is available in OpenAPI 3.1 format:
```
https://partners-backend-1038109371738.europe-west1.run.app/api/v1/openapi.json
```
You can use this to:
* Generate client libraries
* Import into Postman
* Validate requests
## Interactive API Explorer
Try API endpoints directly in the interactive Swagger documentation
## Next Steps
Learn how to authenticate API requests
Create a smart account for your user
Use the TypeScript SDK instead
Complete integration guide
# Optimize Allocations
Source: https://docs.gizatech.xyz/api-reference/optimizer/optimize
POST /api/v1/optimizer/{chain_id}/optimize
Calculate optimal capital allocation across protocols
**SDK Alternative**: Use `giza.optimize(options)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/optimizer)
## Description
Calculates the optimal capital allocation across DeFi lending protocols. Returns the optimal allocation, an action plan to achieve it, and execution-ready calldata.
This endpoint is the core of the **IaaS (Intelligence as a Service)** integration.
## Path Parameters
The blockchain chain ID
## Request Body
Total capital to allocate (as bigint string, e.g., "1000000000" for 1000 USDC)
Token address to optimize for
Current allocations by protocol (protocol name → amount as bigint string)
Example: `{"aave": "500000000", "compound": "500000000"}`
List of protocol names to consider for optimization
Optional constraints for optimization. Each constraint is an object with `kind` and `params`.
**Constraint types and required parameters:**
| Kind | Params | Description |
| ------------------------------------ | -------------------------------------------------------------------- | --------------------------------------------------- |
| `min_protocols` | `min_protocols` (int), `min_fraction_per_protocol` (float, optional) | Minimum number of protocols to use |
| `max_amount_per_protocol` | `protocol` (string), `max_ratio` (float 0-1) | Cap a protocol at a **percentage** of total capital |
| `max_allocation_amount_per_protocol` | `protocol` (string), `max_amount` (int) | Cap a protocol at an **absolute amount** |
| `min_amount` | `min_amount` (int) | Minimum amount for any used protocol |
| `min_allocation_amount_per_protocol` | `protocol` (string), `min_amount` (int) | Minimum amount for a specific protocol |
| `exclude_protocol` | `protocol` (string) | Exclude a protocol from optimization |
**Example:**
```json theme={null}
[
{ "kind": "min_protocols", "params": { "min_protocols": 2 } },
{ "kind": "max_amount_per_protocol", "params": { "protocol": "aave", "max_ratio": 0.5 } },
{ "kind": "exclude_protocol", "params": { "protocol": "compound" } }
]
```
Optional wallet address that will execute the transactions.
Example: `"0x1234567890123456789012345678901234567890"`
## Response
Optimization results
List of protocol allocations with `protocol`, `allocation`, and `apr`
Estimated gas costs
Initial weighted APR before optimization
Final weighted APR after optimization
APR improvement percentage
Estimated total gas cost in USD for executing the rebalancing (optional)
Number of days until APR improvement exceeds gas cost (optional)
Ordered list of actions to execute
`deposit` or `withdraw`
Target protocol
Amount (bigint string)
Execution-ready transaction data
Target contract
Function to call
ABI-encoded parameters
Native token value
Protocol reference
Human-readable description
```bash cURL (Basic) theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/optimizer/8453/optimize" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"total_capital": "1000000000",
"token_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"current_allocations": {
"aave": "500000000",
"compound": "500000000"
},
"protocols": ["aave", "compound", "moonwell", "fluid"],
"wallet_address": "0x1234567890123456789012345678901234567890"
}'
```
```bash cURL (With Constraints) theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/optimizer/8453/optimize" \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{
"total_capital": "1000000000",
"token_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"current_allocations": {
"aave": "500000000",
"compound": "500000000"
},
"protocols": ["aave", "compound", "moonwell", "fluid"],
"wallet_address": "0x1234567890123456789012345678901234567890",
"constraints": [
{ "kind": "min_protocols", "params": { "min_protocols": 2 } },
{ "kind": "max_amount_per_protocol", "params": { "protocol": "aave", "max_ratio": 0.5 } },
{ "kind": "max_amount_per_protocol", "params": { "protocol": "compound", "max_ratio": 0.5 } },
{ "kind": "max_amount_per_protocol", "params": { "protocol": "moonwell", "max_ratio": 0.5 } },
{ "kind": "max_amount_per_protocol", "params": { "protocol": "fluid", "max_ratio": 0.5 } }
]
}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/optimizer/8453/optimize',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify({
total_capital: '1000000000',
token_address: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
current_allocations: {
aave: '500000000',
compound: '500000000',
},
protocols: ['aave', 'compound', 'moonwell', 'fluid'],
wallet_address: '0x1234567890123456789012345678901234567890',
constraints: [
{ kind: 'min_protocols', params: { min_protocols: 2 } },
{ kind: 'max_amount_per_protocol', params: { protocol: 'fluid', max_ratio: 0.5 } }
]
}),
}
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.post(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/optimizer/8453/optimize',
headers={
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
json={
'total_capital': '1000000000',
'token_address': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
'current_allocations': {
'aave': '500000000',
'compound': '500000000',
},
'protocols': ['aave', 'compound', 'moonwell', 'fluid'],
'wallet_address': '0x1234567890123456789012345678901234567890',
'constraints': [
{'kind': 'min_protocols', 'params': {'min_protocols': 2}},
{'kind': 'max_amount_per_protocol', 'params': {'protocol': 'fluid', 'max_ratio': 0.5}}
]
}
)
data = response.json()
```
```json 200 OK theme={null}
{
"optimization_result": {
"allocations": [
{
"protocol": "aave",
"allocation": "700000000",
"apr": 5.5
},
{
"protocol": "compound",
"allocation": "300000000",
"apr": 4.8
}
],
"total_costs": 0.05,
"weighted_apr_initial": 5.0,
"weighted_apr_final": 5.29,
"apr_improvement": 5.8,
"gas_estimate_usd": 2.50,
"break_even_days": 15.3
},
"action_plan": [
{
"action_type": "withdraw",
"protocol": "compound",
"amount": "200000000",
"underlying_amount": "200000000"
},
{
"action_type": "deposit",
"protocol": "aave",
"amount": "200000000"
}
],
"calldata": [
{
"contract_address": "0xA88594D404727625A9437C3f886C7643872296AE",
"function_name": "withdraw",
"parameters": ["200000000"],
"value": "0",
"protocol": "compound",
"description": "Withdraw 200000000 from Compound"
},
{
"contract_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"function_name": "approve",
"parameters": ["0x9c4ec768c28520B50860ea7a15bd7213a9fF58bf", "200000000"],
"value": "0",
"protocol": "aave",
"description": "Approve USDC for Aave"
},
{
"contract_address": "0x9c4ec768c28520B50860ea7a15bd7213a9fF58bf",
"function_name": "supply",
"parameters": ["0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "200000000", "0x0000000000000000000000000000000000000000", "0"],
"value": "0",
"protocol": "aave",
"description": "Deposit 200000000 to Aave"
}
]
}
```
```json 400 Bad Request theme={null}
{
"detail": "Invalid input parameters"
}
```
# Get Protocols
Source: https://docs.gizatech.xyz/api-reference/protocols/get-protocols
GET /api/v1/{chain_id}/{token_address}/protocols
Get available protocols for a token
**SDK Alternative**: Use `giza.protocols(token)` for a simpler TypeScript interface. [See SDK docs](/sdk-reference/giza)
## Description
Retrieves the list of available DeFi protocols for a specific token on a chain, including their current APY and TVL.
## Path Parameters
The blockchain chain ID
The token address (e.g., USDC address)
## Response
List of available protocols
Protocol name (e.g., "aave", "compound")
Whether the protocol is currently available
Protocol description
Total Value Locked
Current Annual Percentage Yield
Available pools within the protocol
Protocol creation date
Last update date
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913/protocols"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913/protocols'
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913/protocols'
)
data = response.json()
```
```json 200 OK theme={null}
{
"protocols": [
{
"name": "aave",
"available": true,
"description": "Aave v3 lending protocol",
"tvl": 1500000000,
"apy": 5.5,
"pools": [
{
"name": "USDC",
"apy": 5.5
}
],
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-20T12:00:00Z"
},
{
"name": "compound",
"available": true,
"description": "Compound v3 lending protocol",
"tvl": 800000000,
"apy": 4.8,
"pools": [
{
"name": "USDC",
"apy": 4.8
}
],
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-20T12:00:00Z"
},
{
"name": "moonwell",
"available": true,
"description": "Moonwell lending protocol",
"tvl": 200000000,
"apy": 6.2,
"pools": [],
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-20T12:00:00Z"
}
]
}
```
# Get Protocols Supply
Source: https://docs.gizatech.xyz/api-reference/protocols/get-protocols-supply
GET /api/v1/{chain_id}/{token_address}/protocols/supply
Get the total supply for each protocol
## Description
Retrieves the total supply and available tokens for each protocol on a chain.
## Path Parameters
The blockchain chain ID
The token address
## Response
Returns supply information for each protocol.
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913/protocols/supply"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913/protocols/supply'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"protocols": [
{
"name": "aave",
"total_supply": 1500000000,
"available_liquidity": 500000000
},
{
"name": "compound",
"total_supply": 800000000,
"available_liquidity": 200000000
}
]
}
```
# Get Reward History
Source: https://docs.gizatech.xyz/api-reference/rewards/get-history
GET /api/v1/{chain_id}/rewards/{wallet}/history
Get token reward history
## Description
Retrieves the paginated token reward history for a wallet.
## Path Parameters
The blockchain chain ID
The smart account wallet address
## Query Parameters
Page number (starts at 1)
Items per page (max 100)
Sort order: `date_desc` or `date_asc`
## Response
List of reward entries
Reward date
Token symbol
Reward amount
USD value
Transaction hash
Whether this reward is staked
Pagination info
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x.../history?page=1&limit=20"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x.../history?page=1&limit=20'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"rewards": [
{
"date": "2024-01-20T12:00:00Z",
"token_symbol": "AAVE",
"amount": 1.5,
"dollar_value": 150.0,
"transaction_hash": "0xabc...",
"is_staked": false
}
],
"pagination": {
"total_items": 10,
"total_pages": 1,
"current_page": 1,
"items_per_page": 20
}
}
```
# Get Reward Status
Source: https://docs.gizatech.xyz/api-reference/rewards/get-status
GET /api/v1/{chain_id}/rewards/{wallet}
Get reward staking status
## Description
Retrieves the reward staking status for a wallet.
## Path Parameters
The blockchain chain ID
The smart account wallet address
## Response
Whether rewards are being staked
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x..."
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x...'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"is_staked": false
}
```
# Set Reward Status
Source: https://docs.gizatech.xyz/api-reference/rewards/set-status
POST /api/v1/{chain_id}/rewards/{wallet}
Set reward staking status
## Description
Sets the reward staking status for a wallet.
## Path Parameters
The blockchain chain ID
The wallet address
## Request Body
The desired staking status
## Response
Returns `204 No Content` on success.
```bash cURL theme={null}
curl -X POST "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x..." \
-H "Content-Type: application/json" \
-H "X-Partner-API-Key: your-api-key" \
-H "X-Partner-Name: your-partner-name" \
-d '{"is_staked": true}'
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/rewards/0x...',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Partner-API-Key': 'your-api-key',
'X-Partner-Name': 'your-partner-name',
},
body: JSON.stringify({ is_staked: true }),
}
);
```
```text 204 No Content theme={null}
(empty response body)
```
# Get Statistics
Source: https://docs.gizatech.xyz/api-reference/statistics/get-stats
GET /api/v1/{chain_id}/stats
Get platform statistics
## Description
Retrieves aggregate statistics for the Giza platform on a specific chain.
## Path Parameters
The blockchain chain ID
## Response
Total balance across all agents
Total deposits across all agents
Total number of active users
Total number of transactions
Average APR across all agents
Distribution of liquidity across protocols
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/stats"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/stats'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"total_balance": 15000000.50,
"total_deposits": 14500000.00,
"total_users": 1250,
"total_transactions": 45000,
"total_apr": 5.8,
"liquidity_distribution": {
"initial_deposits": [
{"token": "USDC", "amount": 14500000}
],
"current_tokens": [
{"token": "USDC", "amount": 15000000}
],
"protocols": [
{
"protocol": "aave",
"balances": [{"token": "USDC", "amount": 8000000}]
},
{
"protocol": "compound",
"balances": [{"token": "USDC", "amount": 7000000}]
}
]
}
}
```
# Get TVL
Source: https://docs.gizatech.xyz/api-reference/statistics/get-tvl
GET /api/v1/{chain_id}/tvl
Get current Total Value Locked
## Description
Retrieves the current Total Value Locked (TVL) across all agents on a chain.
## Path Parameters
The blockchain chain ID
## Response
Total Value Locked in USD
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/tvl"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/tvl'
);
const data = await response.json();
```
```json 200 OK theme={null}
{
"tvl": 15000000.50
}
```
# Get Supported Chains
Source: https://docs.gizatech.xyz/api-reference/support/get-chains
GET /api/v1/chains
Get list of supported blockchain chains
## Description
Retrieves the list of blockchain chains supported by Giza.
## Response
List of supported chain IDs
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/chains"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/chains'
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/chains'
)
data = response.json()
```
```json 200 OK theme={null}
{
"chain_ids": [8453, 1, 42161, 137, 84532, 11155111]
}
```
## Chain ID Reference
| Chain ID | Network |
| ---------- | ---------------------- |
| `8453` | Base Mainnet |
| `1` | Ethereum Mainnet |
| `42161` | Arbitrum One |
| `137` | Polygon Mainnet |
| `84532` | Base Sepolia (testnet) |
| `11155111` | Sepolia (testnet) |
# Get Supported Tokens
Source: https://docs.gizatech.xyz/api-reference/support/get-tokens
GET /api/v1/{chain_id}/tokens
Get supported tokens for a chain
## Description
Retrieves the list of supported tokens for a specific blockchain chain.
## Path Parameters
The blockchain chain ID
## Response
List of supported token contract addresses
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/tokens"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/tokens'
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/8453/tokens'
)
data = response.json()
```
```json 200 OK theme={null}
{
"token_addresses": [
"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
]
}
```
## Common Token Addresses
### Base (Chain ID: 8453)
| Token | Address |
| ----- | -------------------------------------------- |
| USDC | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |
### Ethereum (Chain ID: 1)
| Token | Address |
| ----- | -------------------------------------------- |
| USDC | `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48` |
| USDT | `0xdAC17F958D2ee523a2206206994597C13D831ec7` |
# Health Check
Source: https://docs.gizatech.xyz/api-reference/support/healthcheck
GET /api/v1/healthcheck
Check API health status
## Description
Health check endpoint to verify the API is running and accessible.
## Response
Health status message
API version
Current server time (ISO format)
```bash cURL theme={null}
curl "https://partners-backend-1038109371738.europe-west1.run.app/api/v1/healthcheck"
```
```javascript JavaScript theme={null}
const response = await fetch(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/healthcheck'
);
const data = await response.json();
```
```python Python theme={null}
import requests
response = requests.get(
'https://partners-backend-1038109371738.europe-west1.run.app/api/v1/healthcheck'
)
data = response.json()
```
```json 200 OK theme={null}
{
"message": "OK",
"version": "0.1.0",
"time": "2024-01-20T15:30:00Z"
}
```
# Dashboard Guide
Source: https://docs.gizatech.xyz/app-guide/dashboard
Navigate your dashboard, manage funds, and track performance
## Dashboard Overview
After activation, you land on the **dashboard** -- where you monitor your agent, track performance, and manage your funds.
Here's how it's laid out:
* **Overview metrics** at the top -- Current value, Net deposited, Net earned, Net APR, and Active markets
* **Operator button** -- a rotating indicator showing what the agent is doing right now
* **Deposit and Withdraw buttons** -- in the dashboard header
* **Three tabs** below the overview: **Markets**, **Performance**, and **Transactions**
***
## Dashboard Tabs
Shows how your funds are split across protocols.
* **Allocation bar** -- color-coded breakdown of your funds by market
* **Markets table** with columns:
* **Market** -- the pool or vault name
* **Protocols** -- the protocol logo (Aave, Compound, Moonwell, etc.)
* **Allocated** -- what percentage of your balance is in this market
* **Value** -- dollar amount in this market
* **Current APR** -- live APR for this market
* **Edit button** -- click the edit icon next to "Active markets" in the overview to change which markets your agent uses (see [Editing Active Markets](#editing-active-markets))
Shows your returns over time.
* **Performance chart** -- two lines on a time-series chart:
* **Native projection** (green) -- growth from protocol yields alone
* **Total projection** (white, Base only) -- growth including Giza Rewards APR
* **Date filters** -- zoom into different time ranges
* **Yield Projection** subsection:
* **Native APR** -- annualized return from lending protocols
* **Giza APR** (Base only) -- bonus yield from Giza to hit the 15% minimum target
* **Annual Projection** -- estimated 12-month earnings at current rates
A paginated log of every action the agent has taken -- rebalances, deposits, and withdrawals.
Each row shows a summary with status, amount, allocation percentage, and date. Expand a row to see on-chain details:
* Protocols involved and amounts moved
* APR and utilization rate per transaction
* Block explorer link ("Show Transaction")
* **Giza Thoughts** button -- opens the agent's reasoning log explaining why it made this move (see [Giza Thoughts](#giza-thoughts))
***
## Understanding Your Metrics
| Metric | Description |
| ------------------ | -------------------------------------------------------------------------------------------- |
| **Current value** | USD value of your position across all protocols. |
| **Net deposited** | Total deposited minus total withdrawn. Hover for the full breakdown. |
| **Net earned** | Your profit after the 10% fee. Hover for: Earned - Fee = Net earned. |
| **Net APR** | Your annualized return after fees. Hover for: Native APR + Giza Rewards APR - Fee = Net APR. |
| **Active markets** | How many protocol pools the agent is using, with protocol logos. |
**Net APR breakdown:** The tooltip shows Native APR (from lending protocols) + Giza Rewards APR (Base only, tops up to 15% minimum) - Fee (10%) = Net APR. On Base, if Native APR is below 15%, Giza covers the gap. As Native APR climbs toward 15%, the Giza Rewards portion shrinks to 0%.
***
## Depositing More Funds
Click **Deposit** in the dashboard header.
Type the amount you want to deposit. The modal title shows **"Deposit"**.
Approve the transaction in your wallet. The modal shows **"Deposit processing"** while confirming.
Once confirmed, you'll see **"Deposit successful"** with: **"You added to your Agent."**
The agent stays active and folds the new funds into its next optimization cycle.
***
## Withdrawing and Deactivating
### Partial Withdrawal
Click **Withdraw** in the dashboard header. The modal title shows **"Withdraw your funds"**.
Enter how much you want to pull out.
* The modal shows the minimum balance to keep the agent running: **"At least is required to keep the agent running."**
* To withdraw everything, you need to deactivate (see below).
Click **Withdraw** and approve the transaction in your wallet.
A 10% fee is taken from your gains, paid in the same tokens you're withdrawing. This fee never touches your principal. See [Fees & Rewards](/app-guide/fees-and-rewards) for details.
### Full Withdrawal (Deactivation)
Two ways to deactivate:
1. **From the Withdraw modal** -- Click the **deactivate** link in the text "To withdraw all your funds, deactivate instead." The modal switches to deactivation mode and sets the amount to your full balance. Click the red **Deactivate** button.
2. **From Agent Details** -- Open Agent Details (see [Agent Account Details](#agent-account-details)) and click the red **Deactivate** button at the bottom.
Deactivating shuts down your agent entirely. To start earning again, you'd go through the activation flow from scratch. The 10% fee on gains is deducted at withdrawal.
Once deactivated, the agent exits all protocol positions and sends your funds (minus the fee on gains) back to your wallet.
***
## Agent Account Details
Click the account button in the dashboard header to open Agent Details. The modal contains:
* **Smart account address** -- the on-chain account your agent operates through. You can copy the address or open it in the block explorer.
* **Upgrade permissions** -- if an upgrade is available, you'll see an **"Upgrade permissions"** section: "Upgrade your agent permissions to support new protocols and more markets." Click **Upgrade** and approve in your wallet.
* **Deactivate agent** -- red Deactivate button at the bottom (see [Full Withdrawal](#full-withdrawal-deactivation))
Upgrading permissions doesn't touch your funds or positions. It just lets the agent work with newly supported protocols.
***
## Editing Active Markets
You can change which markets your agent uses after activation:
Click the **edit icon** next to "Active markets" in the dashboard overview. The modal reads **"Edit active markets"**.
Same pool selection interface as the activation wizard. Add or remove markets -- at least 2 must stay enabled.
Confirm your changes. The agent picks up the new market selection on its next cycle. No need to deactivate or re-activate.
***
## Giza Thoughts
**Giza Thoughts** lets you see why the agent did what it did. You can open it from:
* The **Thoughts** button on any transaction row in the Transactions tab
* The **Operator button** on the dashboard
The modal shows the agent's reasoning -- which protocols it looked at, what it decided, and why it moved funds.
***
## Multi-Chain Support
Use the **network selector** in the top nav to switch chains.
Each chain runs its own agent -- what happens on Base doesn't affect Arbitrum, and vice versa. You can run agents on multiple chains at the same time.
| Chain | Token | Protocols |
| -------- | ----- | ----------------------------------------------------- |
| Base | USDC | Aave, Compound, Moonwell, Fluid, Euler, Morpho vaults |
| Arbitrum | USDC | Aave, Compound, Fluid, Euler, Morpho vaults |
| Plasma | USDT0 | Aave, Fluid, Euler |
See [Supported Chains & Protocols](/app-guide/supported-chains-and-protocols) for the full market-by-market breakdown.
***
## Next Steps
Fee structure and the Giza Rewards program
Common questions about the Giza App
# FAQ
Source: https://docs.gizatech.xyz/app-guide/faq
Frequently asked questions about the Giza App
Your funds sit in a self-custodial smart account that only you control. The agent can only interact with the lending protocols you've selected. Giza never has custody of your funds.
It watches APRs across your selected markets and runs the numbers on where your funds will earn the most. When it finds a better option, it moves funds there automatically. You can see the agent's reasoning by clicking **Giza Thoughts** on any transaction.
DeFi carries real risks -- smart contract bugs, liquidity crunches, oracle failures. Giza spreads your funds across multiple audited protocols to reduce exposure, but can't eliminate risk entirely. Your principal is never used to pay fees.
There's no fixed schedule. The agent watches rates and rebalances when it finds a meaningful improvement. You can see every move in the Transactions tab.
Giza takes 10% of the yield earned -- never your principal. Deposits, withdrawals, and rebalances are free. See [Fees & Rewards](/app-guide/fees-and-rewards) for the full breakdown.
Hit **Withdraw** on your dashboard, then click the **deactivate** link. The agent exits all positions and sends your funds back. The 10% fee only applies to yield earned.
Your yield (minus the 10% fee) goes back to your wallet along with your principal. Any reward tokens earned from protocol incentives are included.
Yes. Each chain runs its own agent independently. Use the network selector in the top nav to switch between them.
MetaMask, WalletConnect (300+ wallets), Rainbow, Coinbase Wallet, Binance Wallet, Safe (multisig), and any detected Ethereum wallet. See [Getting Started](/app-guide/getting-started) for details.
Base (USDC), Arbitrum (USDC), and Plasma (USDT0). See [Supported Chains & Protocols](/app-guide/supported-chains-and-protocols) for the full list of lending markets per chain.
# Fees & Rewards
Source: https://docs.gizatech.xyz/app-guide/fees-and-rewards
Fee structure and the Giza Rewards program
## Fees
Giza takes a **10% cut of yield earned** -- never your principal. Deposits, withdrawals, and rebalances are free.
| Action | Fee |
| ----------------- | --------------------------------------------- |
| Deposit | Free |
| Withdrawal | Free |
| Gas (rebalancing) | Free -- agent covers all gas after activation |
| Yield earned | 10% performance fee |
| Principal | No fee ever |
The 10% fee only applies to yield. Your deposited principal is never touched. The fee is deducted at withdrawal.
***
## Giza Rewards (Base Only)
On Base, Giza guarantees a **15% minimum APR target** through Giza Rewards:
* If your Native APR from lending is below 15%, Giza makes up the difference
* As Native APR rises toward 15%, the Giza Rewards portion drops toward 0%
* Once Native APR passes 15%, Giza Rewards is 0% -- your returns come entirely from protocol yields
### How the APR Breakdown Works
| Scenario | Native APR | Giza Rewards APR | Net APR (after 10% fee) |
| ---------- | ---------- | ---------------- | ----------------------- |
| Low rates | 5% | 10% | \~13.5% |
| Mid rates | 10% | 5% | \~13.5% |
| High rates | 15%+ | 0% | \~13.5%+ |
The dashboard tooltip shows: **Native APR + Giza Rewards APR - Fee = Net APR**.
### Reward Tokens
Reward tokens earned through protocol incentives include:
* **COMP** (Compound)
* **WELL** (Moonwell)
* **MORPHO** (Morpho)
* **SEAM** (Seamless)
* **WXPL** (Plasma)
* **ARB** (Arbitrum)
* **FLUID** (Fluid)
Giza Rewards APR is only available on Base. Other chains earn yield from protocol rates alone.
***
## Next Steps
Monitor performance, deposit, and withdraw
Common questions about fees, rewards, and risk
# Getting Started
Source: https://docs.gizatech.xyz/app-guide/getting-started
Set up your Giza agent — from connecting your wallet to automated yield optimization
## What is the Giza App?
The Giza App runs an agent that moves your stablecoins between DeFi lending protocols to get you the best yield. You deposit into a smart account you control, pick a strategy, and the agent handles the rest -- watching rates, shifting funds when it finds something better, and covering gas for every rebalance after activation.
## Prerequisites
### Supported Wallets
You can connect to the Giza App with any of these:
* **MetaMask**
* **WalletConnect** (supports 300+ wallets)
* **Rainbow**
* **Coinbase Wallet**
* **Binance Wallet**
* **Safe** (multisig)
* Any detected Ethereum wallet in your browser
The Giza App uses wallet-only login. Social login (email, Google, Apple) is not yet available. You need a supported Ethereum wallet.
### Supported Chains and Tokens
| Chain | Token | Notes |
| -------- | ----- | ----------------------------------------------- |
| Base | USDC | Giza Rewards APR available (15% minimum target) |
| Arbitrum | USDC | |
| Plasma | USDT0 | |
See [Supported Chains & Protocols](/app-guide/supported-chains-and-protocols) for the full list of lending markets per chain.
You'll need a small amount of the chain's native token (e.g., ETH on Base or Arbitrum) for the initial deposit transaction. After that, the agent covers all gas fees.
## Connect Your Wallet
Go to [app.gizatech.xyz](https://app.gizatech.xyz) in your browser.
Click the **Connect your wallet** button on the home page.
Select your wallet from the list -- MetaMask, WalletConnect, Rainbow, Coinbase Wallet, Binance Wallet, Safe, or another detected Ethereum wallet.
Follow your wallet's prompts to approve the connection.
If your wallet isn't whitelisted, you'll see: **"Your wallet isn't whitelisted for access. Please try a different wallet."** The app will ask you to switch wallets.
If you already have an active agent, you'll go straight to your dashboard after connecting.
## Activation Wizard
The activation flow has six steps:
```mermaid theme={null}
graph LR
A[Select Network] --> B[Select Strategy]
B --> C[Enter Amount]
C --> D[Select Markets]
D --> E[Review]
E --> F[Agent Launching]
```
Choose which chain to deploy your agent on. The heading reads **"Select chain to proceed"**.
Available networks: **Base** (USDC), **Arbitrum** (USDC), **Plasma** (USDT0).
If you already have an active agent on a chain, selecting it takes you to that agent's dashboard.
New to DeFi? Base is a solid starting point -- fast transactions, low gas, and you get the Giza Rewards APR (15% minimum target).
Choose your **Agent Strategy**:
* **Auto** -- "Your agent will be motivated to secure the highest yield for your stable investments. You can always customize your options if you wish."
* **Custom** -- "Your agent adapts to your preferences, letting you adjust parameters anytime. Choose protocols, markets, and percentages, and it will optimize within those settings."
Auto means the agent picks and manages every available pool on the chain. Custom lets you hand-pick which markets the agent uses in the next step.
Enter the amount of tokens you want to deposit. The heading reads **"Enter amount"**.
* The minimum deposit is shown in the app (default: \$1 equivalent).
* You'll need a small amount of the chain's native token for gas on this first transaction.
* After activation, the agent handles all gas going forward.
If you chose Custom, you'll see the **"Pick markets for agent execution"** screen.
* Browse or search the available pools and protocols.
* Pick at least **2 markets** for the agent to work with.
* Each market shows its current deposits (TVL) and APY.
* You can filter by protocol and sort by deposits or APY.
More markets doesn't mean more risk -- it just gives the agent more room to find better rates.
If you chose Auto, this step is skipped. All active markets on the chain are selected automatically.
The review screen shows a summary of your deposit:
* **Your Deposit** -- the amount you're depositing (editable)
* **You'll earn /per year** -- projected annual earnings at current rates
* **APR** -- simulated APR for your allocation (hover for the Native APR + Giza APR breakdown on Base)
* **Markets** -- how many markets the agent will use
* **Allocate to at least** -- minimum number of markets for diversification
Click **Deposit** and confirm the transaction in your wallet.
Projected earnings are estimates based on current protocol rates. Actual APR changes as market conditions shift.
After confirming, you'll see a loading screen: **"Your agent has landed in Giza World. It's currently navigating the protocol web to secure your optimal yield."**
You'll be redirected to your dashboard once activation finishes.
## What Happens After Activation
Once active, the agent gets to work right away. It watches APRs across your selected markets, figures out where your funds will earn the most, and moves them when it spots a better rate. You don't pay gas for any of these rebalances -- the agent covers that.
### Fee Structure
Giza takes a **10% cut of yield earned** -- never your principal. Deposits, withdrawals, and rebalances are all free.
| Action | Fee |
| ----------------- | -------------------- |
| Deposit | Free |
| Withdrawal | Free |
| Rebalancing (gas) | Covered by the agent |
| Yield earned | 10% fee |
| Principal | No fee ever |
## Next Steps
Navigate your dashboard, add funds, and manage your agent
Fee structure and the Giza Rewards program
# Supported Chains & Protocols
Source: https://docs.gizatech.xyz/app-guide/supported-chains-and-protocols
Chains, deposit assets, and lending protocols available in the Giza App
The Giza App currently supports **3 chains** with a total of **26 lending protocol markets** your agent can allocate across.
## Overview
| Chain | Deposit Asset | Protocol Families | Markets |
| ------------ | ------------- | ---------------------------------------------- | :-----: |
| **Base** | USDC | Aave, Compound, Moonwell, Fluid, Euler, Morpho | 11 |
| **Arbitrum** | USDC | Aave, Compound, Fluid, Euler, Morpho | 11 |
| **Plasma** | USDT0 | Aave, Fluid, Euler | 4 |
***
## Base — USDC
Deposit token: **USDC** (`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`)
| # | Protocol | Market |
| -- | ------------ | ---------------------- |
| 1 | **Aave** | Aave USDC |
| 2 | **Compound** | Compound USDC |
| 3 | **Moonwell** | Moonwell USDC |
| 4 | **Fluid** | Fluid USDC |
| 5 | **Euler** | Euler USDC |
| 6 | **Morpho** | Gauntlet USDC Prime |
| 7 | **Morpho** | Moonwell Flagship USDC |
| 8 | **Morpho** | Seamless USDC Vault |
| 9 | **Morpho** | Steakhouse USDC |
| 10 | **Morpho** | Universal USDC |
| 11 | **Morpho** | Smokehouse USDC |
Base is the only chain with the [Giza Rewards program](/app-guide/fees-and-rewards#giza-rewards-base-only) — a 15% minimum APR target where Giza covers any shortfall.
***
## Arbitrum — USDC
Deposit token: **USDC** (`0xaf88d065e77c8cC2239327C5EDb3A432268e5831`)
| # | Protocol | Market |
| -- | ------------ | -------------------------- |
| 1 | **Aave** | Aave USDC |
| 2 | **Compound** | Compound USDC |
| 3 | **Fluid** | Fluid USDC |
| 4 | **Euler** | Euler USDC |
| 5 | **Euler** | Euler Yield USDC |
| 6 | **Morpho** | Gauntlet USDC Core |
| 7 | **Morpho** | Gauntlet USDC Prime |
| 8 | **Morpho** | Clearstar USDC Reactor |
| 9 | **Morpho** | Hyperithm USDC |
| 10 | **Morpho** | MEV Capital USDC |
| 11 | **Morpho** | Steakhouse High Yield USDC |
***
## Plasma — USDT0
Deposit token: **USDT0** (`0xB8CE59FC3717ada4C02eaDF9682A9e934F625ebb`)
| # | Protocol | Market |
| - | --------- | ---------------------- |
| 1 | **Aave** | Aave USDT0 |
| 2 | **Fluid** | Fluid USDT0 |
| 3 | **Euler** | Frontier Etherfi USDT0 |
| 4 | **Euler** | Frontier Ethena USDT0 |
***
## Reward Tokens
When your agent interacts with protocols that distribute incentive tokens, those rewards accrue to your smart account. Reward tokens vary by chain:
| Token | Chains |
| ---------------------- | ---------------------- |
| **COMP** (Compound) | Base, Arbitrum |
| **WELL** (Moonwell) | Base |
| **MORPHO** (Morpho) | Base, Arbitrum |
| **SEAM** (Seamless) | Base |
| **ARB** (Arbitrum) | Arbitrum |
| **FLUID** (Fluid) | Base, Arbitrum, Plasma |
| **WXPL** (Wrapped XPL) | Plasma |
| **rEUL** (Euler) | Base |
More chains and protocols are regularly being added. Check back for updates or follow [@gizatechxyz](https://x.com/gizatechxyz) for announcements.
# Constraints
Source: https://docs.gizatech.xyz/developers/architecture/constraints
All constraint types for controlling agent and optimizer behavior
## Overview
Constraints control how agents and the optimizer allocate capital. Use them to enforce diversification, cap exposure, exclude protocols, and set minimum allocations.
Constraints apply to both the Agentic approach (passed during `agent.activate()`) and the IaaS approach (passed to `giza.optimize()`).
## Constraint Types
```typescript theme={null}
enum WalletConstraints {
MIN_PROTOCOLS = 'min_protocols',
MAX_AMOUNT_PER_PROTOCOL = 'max_amount_per_protocol',
MAX_ALLOCATION_AMOUNT_PER_PROTOCOL = 'max_allocation_amount_per_protocol',
MIN_AMOUNT = 'min_amount',
MIN_ALLOCATION_AMOUNT_PER_PROTOCOL = 'min_allocation_amount_per_protocol',
EXCLUDE_PROTOCOL = 'exclude_protocol',
}
```
## Reference
### MIN\_PROTOCOLS
Require diversification across a minimum number of protocols.
```typescript theme={null}
{
kind: WalletConstraints.MIN_PROTOCOLS,
params: {
min_protocols: 2,
min_fraction_per_protocol: 0.1 // Optional, default 0.05 (5%)
}
}
// Always diversify across at least 2 protocols, each with at least 10%
```
| Parameter | Type | Required | Description |
| --------------------------- | ------ | -------- | ---------------------------------------------------------------- |
| `min_protocols` | number | Yes | Minimum number of protocols to receive allocation |
| `min_fraction_per_protocol` | number | No | Minimum fraction each protocol must receive (0-1). Default: 0.05 |
### MAX\_AMOUNT\_PER\_PROTOCOL
Cap a specific protocol to a **percentage** of total capital.
```typescript theme={null}
{
kind: WalletConstraints.MAX_AMOUNT_PER_PROTOCOL,
params: {
protocol: "aave",
max_ratio: 0.5 // 50% of total capital
}
}
```
| Parameter | Type | Required | Description |
| ----------- | ------ | -------- | --------------------------------------- |
| `protocol` | string | Yes | Protocol to constrain |
| `max_ratio` | number | Yes | Maximum fraction of total capital (0-1) |
Requires a separate constraint for **each protocol** you want to limit. Uses `max_ratio` (0-1), not `max_amount`.
### MAX\_ALLOCATION\_AMOUNT\_PER\_PROTOCOL
Cap a specific protocol to an **absolute amount**.
```typescript theme={null}
{
kind: WalletConstraints.MAX_ALLOCATION_AMOUNT_PER_PROTOCOL,
params: {
protocol: "moonwell",
max_amount: 2000000000 // 2000 USDC (6 decimals)
}
}
```
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | ------------------------------------------------ |
| `protocol` | string | Yes | Protocol to constrain |
| `max_amount` | number | Yes | Maximum absolute amount in token's smallest unit |
### MIN\_AMOUNT
Set a minimum allocation for any protocol that receives funds. Prevents dust allocations.
```typescript theme={null}
{
kind: WalletConstraints.MIN_AMOUNT,
params: { min_amount: 100000000 } // 100 USDC
}
```
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | --------------------------------------- |
| `min_amount` | number | Yes | Minimum amount in token's smallest unit |
### MIN\_ALLOCATION\_AMOUNT\_PER\_PROTOCOL
Ensure a specific protocol receives at least a minimum amount if it's used.
```typescript theme={null}
{
kind: WalletConstraints.MIN_ALLOCATION_AMOUNT_PER_PROTOCOL,
params: {
protocol: "aave",
min_amount: 500000000 // 500 USDC
}
}
```
| Parameter | Type | Required | Description |
| ------------ | ------ | -------- | --------------------------------------- |
| `protocol` | string | Yes | Protocol to constrain |
| `min_amount` | number | Yes | Minimum amount in token's smallest unit |
### EXCLUDE\_PROTOCOL
Blacklist a protocol entirely. The optimizer will never allocate to it.
```typescript theme={null}
{
kind: WalletConstraints.EXCLUDE_PROTOCOL,
params: { protocol: "compound" }
}
```
| Parameter | Type | Required | Description |
| ---------- | ------ | -------- | ------------------- |
| `protocol` | string | Yes | Protocol to exclude |
## MAX\_AMOUNT vs MAX\_ALLOCATION\_AMOUNT
| Constraint | Parameter | Limits by |
| ------------------------------------ | ---------------------- | ---------------------------------- |
| `MAX_AMOUNT_PER_PROTOCOL` | `max_ratio` (0-1) | **Percentage** of total capital |
| `MAX_ALLOCATION_AMOUNT_PER_PROTOCOL` | `max_amount` (integer) | **Absolute amount** in token units |
Both require the `protocol` parameter.
## Combining Constraints
```typescript theme={null}
await agent.activate({
owner: userWallet,
token: USDC_ADDRESS,
protocols: ['aave', 'compound', 'moonwell', 'fluid'],
txHash: depositTxHash,
constraints: [
// Diversify across at least 3 protocols
{
kind: WalletConstraints.MIN_PROTOCOLS,
params: { min_protocols: 3 }
},
// Cap each protocol at 40%
{
kind: WalletConstraints.MAX_AMOUNT_PER_PROTOCOL,
params: { protocol: 'aave', max_ratio: 0.4 }
},
{
kind: WalletConstraints.MAX_AMOUNT_PER_PROTOCOL,
params: { protocol: 'compound', max_ratio: 0.4 }
},
{
kind: WalletConstraints.MAX_AMOUNT_PER_PROTOCOL,
params: { protocol: 'moonwell', max_ratio: 0.4 }
},
{
kind: WalletConstraints.MAX_AMOUNT_PER_PROTOCOL,
params: { protocol: 'fluid', max_ratio: 0.4 }
},
// Cap newer protocol at absolute 2000 USDC
{
kind: WalletConstraints.MAX_ALLOCATION_AMOUNT_PER_PROTOCOL,
params: { protocol: 'fluid', max_amount: 2000000000 }
},
// No dust allocations
{
kind: WalletConstraints.MIN_AMOUNT,
params: { min_amount: 500000000 }
}
]
});
```
## Next Steps
See constraints in a full integration example
How the optimizer uses constraints
activate() method with constraint parameters
# Optimizer
Source: https://docs.gizatech.xyz/developers/architecture/optimizer
How the Giza Optimizer allocates capital across protocols
## What is the Optimizer?
The Optimizer is a stateless service that calculates optimal capital allocation across DeFi lending protocols. It looks at current APRs, gas costs, and constraints to find the distribution of capital with the highest net return.
## How It Works
```mermaid theme={null}
graph TD
A[Input: Current State] --> B[Fetch Protocol APRs]
A --> C[Get Gas Prices]
A --> D[Load Constraints]
B --> E[Optimization Engine]
C --> E
D --> E
E --> F[Calculate Optimal Allocation]
F --> G[Generate Action Plan]
G --> H[Create Transaction Calldata]
H --> I[Output: Optimization Result]
```
## Two Integration Patterns
### Automatic (Agentic)
Agents use the optimizer automatically on a continuous loop. You activate the agent and it handles optimization internally:
1. Agent calls optimizer with current allocations
2. Optimizer returns optimal allocation + action plan
3. Agent executes the rebalancing transactions
4. Repeat on regular optimization cycles
### Manual (IaaS)
Call the optimizer directly for custom implementations. You receive the optimal allocation and decide whether and when to execute. See the [IaaS Integration Guide](/developers/guides/iaas-integration) for a complete walkthrough.
## Stateless Design
The optimizer is **completely stateless**:
* No storage of historical data
* Each call is independent
* Same inputs return same outputs (for same market conditions)
* No side effects
This means it's predictable, testable, composable, and private -- Giza doesn't store your data.
## Optimization Algorithm
### Factors Considered
| Factor | Description |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| **Protocol APRs** | Real-time APRs from each protocol for the specific token, weighted by allocation size |
| **Gas Costs** | Estimated gas for each rebalancing transaction. Optimization only proceeds if APR improvement exceeds gas costs |
| **Protocol Liquidity** | Available liquidity in each protocol. Won't allocate more than the protocol can efficiently handle |
| **Slippage** | Price impact of large deposits/withdrawals, especially for smaller protocols |
| **Constraints** | User-defined constraints (min protocols, max per protocol, exclusions). See [Constraints](/developers/architecture/constraints) |
| **Transaction Minimization** | Prefers fewer, larger transactions over many small ones to save gas |
### Optimization Steps
1. **Fetch Data** -- Get current APRs, gas prices, liquidity
2. **Apply Constraints** -- Filter out invalid allocations
3. **Calculate Scores** -- Score each possible allocation
4. **Select Optimal** -- Choose highest net return allocation
5. **Generate Plan** -- Create minimal set of transactions
6. **Validate** -- Ensure plan respects all constraints
## Optimizer Output
The optimizer returns three things:
1. **Optimization Result** -- Optimal allocations, APR improvement, gas estimate, break-even days
2. **Action Plan** -- Step-by-step deposit/withdraw instructions to reach the optimal allocation
3. **Execution Calldata** -- Ready-to-execute transaction data (contract addresses, function calls, parameters)
See the [SDK Optimizer Reference](/sdk-reference/optimizer) for the full response types and code examples.
## Best Practices
* **Don't over-optimize** -- Calling too frequently wastes gas. Let APR differences accumulate. Good: every 6-24 hours. Bad: every 5 minutes.
* **Set APR thresholds** -- Only rebalance if improvement exceeds a threshold (e.g., 0.3%)
* **Use constraints** -- Always set constraints to match your risk tolerance
* **Consider gas prices** -- During high gas periods, higher APR improvement is needed to justify rebalancing
## Next Steps
All constraint types for controlling optimization
Complete optimizer API with code examples
Use the optimizer with your own execution infrastructure
See the optimizer in action within a full integration
# Architecture Overview
Source: https://docs.gizatech.xyz/developers/architecture/overview
System components, agent lifecycle, and data flow
## System Architecture
```mermaid theme={null}
graph TB
subgraph "Partner Application"
A[Your App]
end
subgraph "Giza Agent SDK"
B[Giza Client]
C[Agent Class]
D[Optimizer]
end
subgraph "Giza Infrastructure"
E[Backend API]
F[Agent Service]
G[Intelligence-as-a-Service]
end
subgraph "Blockchain"
H[Smart Account]
I[Session Keys]
J[DeFi Protocols]
end
A --> B
B --> C
B --> D
C --> E
D --> G
E --> F
F --> H
H --> I
I --> J
```
## Components
### Giza Client
The entry point for all SDK interactions. Initialize once and reuse throughout your application.
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
```
### Agent Class
Manages a single user's smart account. Handles activation, monitoring, withdrawals, and protocol management.
### Optimizer
A stateless service that calculates optimal capital allocation across DeFi protocols. Used automatically by agents (Agentic approach) or called directly (IaaS approach). See [Optimizer](/developers/architecture/optimizer) for details.
### Smart Accounts
ERC-4337 smart contract wallets powered by ZeroDev. Each user gets a deterministic smart account address where they deposit funds. See [Smart Accounts](/developers/architecture/smart-accounts) for details.
## Agent Lifecycle
Smart account exists but no agent is activated. User funds are not being managed.
Agent initialization in progress. Session keys being granted, initial deposits being allocated. Brief transition state.
Agent is running and optimizing. Capital is deployed across protocols, automatic rebalancing occurs.
Withdrawal in progress. Agent pulling funds from all protocols, revoking permissions. Brief transition state.
Agent stopped, funds returned to user. No active management. Can be reactivated.
Activation encountered an error. Funds remain safe in smart account. User can retry or withdraw.
## Optimization Cycle
Once active, the agent runs a continuous optimization loop:
1. **Monitor** -- Continuously monitors APRs across selected protocols
2. **Analyze** -- Calculates optimal allocation considering APRs, gas costs, slippage, protocol limits, and user constraints
3. **Execute** -- If rebalancing improves net returns (after gas), executes transactions
4. **Report** -- Updates performance metrics and portfolio data
5. **Repeat** -- Continues monitoring for next opportunity
## Data Flow
```mermaid theme={null}
sequenceDiagram
participant App as Your App
participant SDK as Giza SDK
participant API as Giza API
participant Agent as Agent Service
participant SA as Smart Account
participant Protocol as DeFi Protocol
App->>SDK: createAgent(eoa)
SDK->>API: POST /smart-accounts
API-->>SDK: smartAccountAddress
SDK-->>App: Agent handle
Note over App: User deposits to smart account
App->>SDK: agent.activate({owner, token, protocols, txHash})
SDK->>API: POST /wallets (activate)
API->>Agent: Initialize agent
Agent->>SA: Setup session keys
SA-->>Agent: Permissions granted
Agent-->>API: Agent activated
API-->>SDK: ActivateResponse
SDK-->>App: Success
loop Every optimization cycle
Agent->>Protocol: Check APRs
Protocol-->>Agent: Current rates
Agent->>Agent: Calculate optimal allocation
Agent->>SA: Execute rebalancing
SA->>Protocol: Deposit/Withdraw
end
```
## Session Keys
Session keys let agents execute specific functions on behalf of smart accounts without requiring user signatures each time.
1. User grants permissions to a session key when activating the agent
2. Session key has specific capabilities (approved contracts, functions, limits)
3. Agent uses session key to execute rebalancing transactions
4. User can revoke permissions at any time by deactivating
Session keys are time-bound, limited in scope, and revocable. See [Smart Accounts](/developers/architecture/smart-accounts) for the full security model.
## Next Steps
Smart account architecture, ZeroDev, and session keys
Supported protocols by chain
How the optimization engine works
All constraint types for controlling agent behavior
# Protocols
Source: https://docs.gizatech.xyz/developers/architecture/protocols
DeFi lending protocols supported by Giza agents across multiple chains
## Overview
Giza agents optimize yield by deploying capital across **DeFi lending protocols** on multiple blockchains. Users supply assets and earn interest from borrowers.
## Supported Protocols by Chain
### Core Protocols
| Protocol | Description | Key Features |
| ------------ | -------------------------------- | -------------------------------------------------- |
| **Aave** | Decentralized liquidity protocol | Isolated risk pools, audited, deep liquidity |
| **Compound** | Established lending market | Gas-efficient, single collateral model, composable |
| **Moonwell** | Base-native lending protocol | Optimized for Base, community governed |
| **Fluid** | Liquidity protocol | Efficient capital usage |
### Morpho Vaults
Morpho is a lending optimization layer that aggregates liquidity across multiple protocols:
| Vault | Strategy |
| --------------------------------- | ------------------------------------ |
| **Morpho Gauntlet USDC Prime** | Gauntlet-managed prime USDC strategy |
| **Morpho Moonwell Flagship USDC** | Moonwell-backed USDC vault |
| **Morpho Seamless USDC Vault** | Seamless protocol integration |
| **Morpho Steakhouse USDC** | Steakhouse Financial strategy |
| **Morpho Universal USDC** | Universal USDC vault |
| **Morpho Smokehouse USDC** | Smokehouse strategy |
### Euler Vaults
Euler is a non-custodial lending protocol with modular vaults:
| Vault | Strategy |
| -------------- | --------------- |
| **Euler USDC** | Core USDC vault |
**Token:** USDC (6 decimals)
### Core Protocols
| Protocol | Description | Key Features |
| ------------ | ------------------------------ | ------------------------------- |
| **Aave** | Arbitrum deployment of Aave V3 | Lower gas costs, deep liquidity |
| **Compound** | Compound V3 on Arbitrum | Gas-efficient on Arbitrum |
| **Fluid** | Liquidity protocol | Efficient capital usage |
### Morpho Vaults
Morpho vaults available on Arbitrum:
| Vault | Strategy |
| ------------------------------------- | ------------------------------ |
| **Morpho Gauntlet USDC Core** | Core Gauntlet strategy |
| **Morpho Gauntlet USDC Prime** | Prime Gauntlet strategy |
| **Morpho Clearstar USDC Reactor** | Clearstar managed vault |
| **Morpho Hyperithm USDC** | Hyperithm strategy |
| **Morpho MEV Capital USDC** | MEV Capital strategy |
| **Morpho Steakhouse High Yield USDC** | High yield Steakhouse strategy |
### Euler Vaults
Euler vaults available on Arbitrum:
| Vault | Strategy |
| -------------------- | -------------------------- |
| **Euler USDC** | Core USDC vault |
| **Euler Yield USDC** | Yield-optimized USDC vault |
**Token:** USDC (6 decimals)
### Core Protocols
| Protocol | Description | Key Features |
| ------------ | ------------------------ | -------------------------------------- |
| **Aave** | Ethereum mainnet Aave V3 | Original deployment, deepest liquidity |
| **Compound** | Compound V3 on Ethereum | Long mainnet history |
| **Fluid** | Liquidity protocol | Efficient capital usage |
### Morpho Vaults
Morpho vaults on Ethereum:
| Vault | Strategy |
| ----------------------------------- | ----------------------------- |
| **Morpho Usual Boosted USDC** | Usual protocol integration |
| **Morpho Avantgarde USDC Core** | Avantgarde managed strategy |
| **Morpho Turtle USDC** | Turtle capital strategy |
| **Morpho Steakhouse Infinifi USDC** | Steakhouse Infinifi strategy |
| **Morpho Smokehouse USDC** | Smokehouse strategy |
| **Morpho Gauntlet USDC Core** | Core Gauntlet strategy |
| **Morpho Yearn OG USDC** | Yearn Finance strategy |
| **Morpho Hakutora USDC** | Hakutora managed vault |
| **Morpho Coinshift USDC** | Coinshift strategy |
| **Morpho Steakhouse USDC** | Steakhouse Financial strategy |
| **Morpho Gauntlet USDC Prime** | Prime Gauntlet strategy |
| **Morpho Hyperithm USDC** | Hyperithm strategy |
| **Morpho Re7 USDC** | Re7 capital strategy |
| **Morpho Gauntlet USDC Frontier** | Frontier Gauntlet strategy |
| **Morpho Clearstar USDC Reactor** | Clearstar reactor vault |
| **Morpho Alpha USDC Core** | Alpha core strategy |
### Euler Vaults
Euler vaults on Ethereum:
| Vault | Strategy |
| -------------------------- | ------------------------- |
| **Euler Rezerve Markets** | Rezerve managed markets |
| **Euler Frontier Yala** | Yala frontier vault |
| **Euler Frontier MMEV** | MMEV frontier strategy |
| **Euler Frontier MHyper** | MHyper frontier vault |
| **Euler Telos Stream** | Telos streaming strategy |
| **Euler R7 Hyperwave** | R7 hyperwave vault |
| **Euler Sentora RLUSD** | Sentora RLUSD strategy |
| **Euler Frontier Falcon** | Falcon frontier vault |
| **Euler Frontier CAP** | CAP frontier strategy |
| **Euler Frontier Strata** | Strata frontier vault |
| **Euler Prime** | Prime vault strategy |
| **Euler Yield** | Yield-optimized vault |
| **Euler Frontier MApollo** | MApollo frontier strategy |
**Token:** USDC (6 decimals)
### Core Protocols
| Protocol | Description | Key Features |
| --------- | ----------------------------- | ------------------------------------------ |
| **Aave** | Polygon deployment of Aave V3 | Low fees, fast transactions |
| **Fluid** | Liquidity protocol | Efficient capital usage, Polygon-optimized |
### Morpho Vaults
| Vault | Strategy |
| ------------------------ | ---------------------------- |
| **Morpho Compound USDC** | Compound-backed Morpho vault |
**Token:** USDC (6 decimals)
### Core Protocols
| Protocol | Description | Key Features |
| --------- | ---------------------------- | --------------------------- |
| **Aave** | Plasma deployment of Aave V3 | Plasma network optimization |
| **Fluid** | Liquidity protocol | Efficient capital usage |
### Euler Vaults
| Vault | Strategy |
| -------------------------------- | -------------------------------- |
| **Euler Frontier EtherFi USDT0** | EtherFi frontier vault for USDT0 |
| **Euler Frontier Ethena USDT0** | Ethena frontier vault for USDT0 |
**Token:** USDT0 (custom stablecoin on Plasma)
### Core Protocols
| Protocol | Description | Key Features |
| ------------- | -------------------------------- | ------------------------------ |
| **Hyperlend** | Native HyperEVM lending protocol | HyperEVM-specific optimization |
### Morpho Vaults
| Vault | Strategy |
| ------------------------------- | ---------------------------- |
| **Morpho Felix USDT0** | Felix capital USDT0 strategy |
| **Morpho Felix USDT0 Frontier** | Felix frontier USDT0 vault |
| **Morpho Hyperithm USDT0** | Hyperithm USDT0 strategy |
| **Morpho MEV Capital USDT0** | MEV Capital USDT0 vault |
| **Morpho Gauntlet USDT0 Vault** | Gauntlet managed USDT0 vault |
**Token:** USDT0 (custom stablecoin on HyperEVM)
## Supported Tokens by Chain
| Token | Chains | Decimals | Description |
| --------- | --------------------------------- | -------- | ------------------------------------- |
| **USDC** | Base, Arbitrum, Ethereum, Polygon | 6 | USD Coin - primary stablecoin |
| **USDT0** | Plasma, HyperEVM | Variable | Custom stablecoin for specific chains |
## Protocol Selection
### Agent Selection
When activating an agent, you select which protocols it can use:
```typescript theme={null}
await agent.activate({
owner: userWallet,
token: USDC_ADDRESS,
protocols: ['aave', 'compound', 'moonwell'],
txHash: depositTxHash,
});
```
### Getting Available Protocols
Retrieve supported protocols for a token on your chain:
```typescript theme={null}
const { protocols } = await giza.protocols(USDC_ADDRESS);
console.log('Available protocols:', protocols);
// Output depends on chain:
// Base: ['aave', 'compound', 'moonwell', 'fluid', 'morpho_gauntlet_usdc_prime', ...]
// Ethereum: ['aave', 'compound', 'fluid', 'morpho_usual_boosted_usdc', ...]
```
## Protocol Types
### Core Protocols
Traditional lending markets like Aave, Compound, Moonwell, Fluid, and Hyperlend:
* Direct lending/borrowing
* Pool-based liquidity
* Variable APRs based on utilization
* Audited contracts (for established protocols)
### Morpho Vaults
Optimization layer that aggregates liquidity:
* Built on top of existing protocols
* Managed strategies by firms like Gauntlet, Steakhouse, Felix, etc.
* Can produce higher APRs through optimization
* Additional layer of risk management
* Available on most chains with varying strategies
### Euler Vaults
Modular lending protocol:
* Non-custodial
* Permissionless vault creation
* Flexible risk parameters
* Isolated markets
* Frontier vaults for emerging strategies
## Protocol Risks
All DeFi protocols carry risk. Giza agents reduce exposure through diversification and optimization, but users should understand what can go wrong:
### Smart Contract Risk
* Protocols are powered by smart contracts
* Bugs or exploits can lead to loss of funds
* **Mitigation**: Audits, time-tested protocols, bug bounties, diversification
### Liquidity Risk
* Sudden large withdrawals can affect availability
* High utilization may delay withdrawals
* **Mitigation**: Diversification across protocols and chains
### Oracle Risk
* Protocols rely on price oracles
* Oracle failures can cause liquidations or losses
* **Mitigation**: Using protocols with reliable oracle systems
### Protocol Governance Risk
* Protocol parameters can change via governance
* Changes may affect yields or security
* **Mitigation**: Monitoring and automatic rebalancing
### Chain-Specific Risks
* Network outages or congestion
* Bridge vulnerabilities (for L2s)
* Chain reorganizations
* **Mitigation**: Choosing established chains
## Protocol Diversification
Giza agents spread capital across protocols to reduce exposure:
1. No single point of failure
2. Access to the best rates across protocols
3. Liquidity spread across multiple pools
4. Protocol-specific risks stay isolated
## Constraints for Protocol Management
Control protocol usage with constraints:
### Minimum Protocols
Ensure diversification:
```typescript theme={null}
{
kind: 'min_protocols',
params: { min_protocols: 2 }
}
```
### Maximum Allocation
Cap exposure to any single protocol:
```typescript theme={null}
{
kind: 'max_amount_per_protocol',
params: { max_amount: '5000000000' } // 5000 USDC
}
```
### Exclude Protocol
Blacklist specific protocols:
```typescript theme={null}
{
kind: 'exclude_protocol',
params: { protocol: 'fluid' }
}
```
### Protocol-Specific Cap
Limit specific protocols:
```typescript theme={null}
{
kind: 'max_allocation_amount_per_protocol',
params: {
protocol: 'morpho_gauntlet_usdc_prime',
max_amount: '2000000000' // 2000 USDC
}
}
```
## Protocol Performance
### Protocol Discovery
Get available protocols for a token:
```typescript theme={null}
const { protocols } = await giza.protocols(USDC_ADDRESS);
console.log('Available protocols:', protocols);
// ['aave', 'compound', 'moonwell', 'fluid', ...]
// Select protocols for activation
const selectedProtocols = protocols.slice(0, 3);
```
### Historical Performance
Agents track how capital performs across protocols:
```typescript theme={null}
const { performance } = await agent.performance({ from: '2024-01-01 00:00:00' });
// See allocation across protocols over time
performance.forEach(point => {
console.log(`${point.date}:`, point.portfolio);
// { aave: 500, compound: 300, moonwell: 200 }
});
```
## Protocol Updates
### Adding New Protocols
As new protocols launch or existing ones upgrade:
* Giza team evaluates security and liquidity
* Protocols undergo risk assessment
* If approved, added to supported list
* Agents can automatically use new protocols
### Updating Agent Protocols
Change protocols for an active agent:
```typescript theme={null}
await agent.updateProtocols(['aave', 'compound', 'moonwell', 'fluid']);
```
Updating protocols triggers rebalancing, which incurs gas costs.
## Next Steps
How Giza optimizes across protocols
How agents interact with protocols
Control protocol usage with constraints
Get started with your first agent
# Smart Accounts
Source: https://docs.gizatech.xyz/developers/architecture/smart-accounts
Smart accounts, ZeroDev, session keys, and gas management
## What are Smart Accounts?
Smart accounts are **smart contract wallets** with gasless transactions, session keys, and programmable permissions. In Giza, every user gets a smart account -- this is the deposit address for agent-managed funds.
Unlike regular wallets (EOAs - Externally Owned Accounts), smart accounts:
* Are smart contracts, not just private key pairs
* Can execute logic and have programmable rules
* Enable gasless transactions through paymasters
* Support session keys for delegated permissions
* Can batch multiple transactions together
## Architecture
```mermaid theme={null}
graph LR
A[User's Origin Wallet
EOA or Smart Wallet] -->|controls| B[Smart Account
Contract]
B -->|grants| C[Session Keys]
C -->|used by| D[Giza Agent]
D -->|executes| E[DeFi Protocols]
```
## ZeroDev Integration
Giza smart accounts are powered by **[ZeroDev](https://zerodev.app/)**, an account abstraction infrastructure provider.
Follows the official Ethereum account abstraction standard for maximum compatibility and security.
Widely deployed across many applications and managing significant assets on-chain.
Agents can execute rebalancing without users paying gas for each transaction.
Time-bound delegated permissions that work well for autonomous agents.
## Deterministic Addresses
Smart accounts are **deterministic** - the same origin wallet always generates the same smart account address.
This means:
* Safe to call `giza.createAgent(eoa)` multiple times
* Users get the same address across sessions
* No risk of losing funds to a "new" address
See createAgent() for implementation details
## Smart Account Lifecycle
```mermaid theme={null}
graph TD
A[Origin Wallet] -->|giza.createAgent| B[Smart Account Created]
B -->|User deposits| C[Smart Account Funded]
C -->|agent.activate| D[Session Keys Granted]
D -->|Agent manages| E[Active Optimization]
E -->|agent.withdraw / agent.deactivate| F[Session Keys Revoked]
F -->|re-activate| D
```
### States
1. **Created**: Smart account exists on-chain but empty
2. **Funded**: User has deposited tokens
3. **Active**: Agent has session key permissions, actively managing
4. **Deactivated**: Permissions revoked, agent no longer managing
## Backend Wallet
The `backendWallet` is a Giza-controlled wallet that:
* Holds session keys to execute transactions
* Acts on behalf of the smart account (with limited permissions)
* Pays gas fees for agent operations
* Is revocable at any time by the user
The backend wallet never controls user funds directly.
It only has permission to call specific functions on specific contracts.
## Session Keys & Permissions
When an agent is activated, the smart account grants **session keys** to the backend wallet with specific permissions:
### Permission Structure
| Permission Type | Description |
| ------------------ | -------------------------------------------------- |
| Approved Targets | Specific protocol contracts (Aave, Compound, etc.) |
| Approved Functions | supply, withdraw, transfer, etc. |
| Transaction Limits | Max amounts per transaction |
### Security Guarantees
Session keys can ONLY:
* Call approved protocol contracts
* Execute approved functions (deposit, withdraw, swap)
* Within approved time windows
* Up to specified limits
Users can deactivate agents at any time, immediately revoking all session key permissions.
Users always retain ultimate control via their origin wallet. Giza never has custody of funds.
## Gas Management
Smart accounts give users **gasless transactions**:
```mermaid theme={null}
graph LR
A[Agent Decides to Rebalance] --> B[Backend Wallet Signs Tx]
B --> C[Paymaster Pays Gas]
C --> D[Smart Account Executes]
D --> E[Protocol Interaction]
F[User] -.pays nothing.-> D
```
How it works:
1. Agent determines optimal rebalancing is needed
2. Backend wallet crafts and signs the transaction
3. Giza's paymaster sponsors the gas fee
4. Smart account executes the transaction
5. User pays nothing for the rebalancing operation
Gas costs are:
* Covered by Giza during active management
* Factored into the performance fee structure
* Optimized through transaction batching
## Troubleshooting
Check:
* Origin wallet is a valid Ethereum address (0x + 40 hex chars)
* Chain is supported
* API credentials are correct
Make sure:
* You're using the same EOA as when it was created
* You're querying the correct chain
* The smart account was actually created (check blockchain explorer)
Verify:
* Transaction was sent to correct `smartAccountAddress`
* Transaction confirmed on-chain (check explorer)
* You're checking the right chain
* Agent was activated after deposit
## Next Steps
Agent lifecycle and system components
Complete smart account API documentation
Full integration tutorial
Common issues and solutions
# Error Handling
Source: https://docs.gizatech.xyz/developers/guides/error-handling
Error handling strategies
## Error Types
The SDK provides specific error classes:
### ValidationError
Input validation failures:
```typescript theme={null}
import { ValidationError } from '@gizatech/agent-sdk';
import type { Address } from '@gizatech/agent-sdk';
try {
await giza.createAgent('invalid-address' as Address);
} catch (error) {
if (error instanceof ValidationError) {
// Invalid input
console.error('Validation failed:', error.message);
showUserError('Please provide a valid Ethereum address');
}
}
```
### GizaAPIError
API errors (4xx, 5xx):
```typescript theme={null}
import { GizaAPIError } from '@gizatech/agent-sdk';
try {
await agent.activate({
owner: userWallet,
token: USDC,
protocols: ['aave', 'compound'],
txHash: depositTxHash,
});
} catch (error) {
if (error instanceof GizaAPIError) {
console.error('API error:', {
status: error.statusCode,
message: error.message,
details: error.details
});
if (error.statusCode === 401) {
// Authentication issue
checkAPICredentials();
} else if (error.statusCode === 429) {
// Rate limited
retryWithBackoff();
}
}
}
```
### TimeoutError
Request timeouts:
```typescript theme={null}
import { TimeoutError } from '@gizatech/agent-sdk';
try {
await agent.withdraw();
} catch (error) {
if (error instanceof TimeoutError) {
console.error('Request timed out');
showMessage('Operation taking longer than expected. Please try again.');
}
}
```
### NotImplementedError
Features not yet available:
```typescript theme={null}
import { NotImplementedError } from '@gizatech/agent-sdk';
try {
await someOperation();
} catch (error) {
if (error instanceof NotImplementedError) {
// Feature not available
console.log('This feature is not yet supported');
}
}
```
## Error Handling Patterns
### Retry with Exponential Backoff
```typescript theme={null}
async function retryOperation(
operation: () => Promise,
maxRetries = 3
): Promise {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
if (i === maxRetries - 1) throw error;
if (error instanceof GizaAPIError && error.statusCode >= 500) {
// Server error, retry
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
} else {
// Client error, don't retry
throw error;
}
}
}
throw new Error('Max retries exceeded');
}
```
### User-Friendly Messages
```typescript theme={null}
function getUserFriendlyError(error: unknown): string {
if (error instanceof ValidationError) {
return 'Please check your input and try again.';
} else if (error instanceof GizaAPIError) {
if (error.statusCode === 404) {
return 'Agent not found. Please create one first.';
} else if (error.statusCode === 429) {
return 'Too many requests. Please wait a moment.';
}
return 'An error occurred. Please try again later.';
} else if (error instanceof TimeoutError) {
return 'Request timed out. Please check your connection.';
}
return 'An unexpected error occurred.';
}
```
## Best Practices
1. **Always use try-catch** around SDK calls
2. **Check error types** with `instanceof`
3. **Log errors** for debugging
4. **Show user-friendly messages** to users
5. **Implement retry logic** for transient failures
6. **Monitor error rates** in production
7. **Have fallbacks** for non-critical features
## Next Steps
Common issues and solutions
Full integration tutorial
# IaaS Integration Guide
Source: https://docs.gizatech.xyz/developers/guides/iaas-integration
Intelligence as a Service - Use Giza's Optimizer as your optimization brain
## Overview
**Intelligence as a Service (IaaS)** gives you access to Giza's Optimizer as a stateless service. If you already have execution infrastructure (smart accounts, transaction execution, capital management), you can use Giza's optimization engine to get optimal capital allocations without giving up control.
## What is IaaS?
IaaS means you bring your own:
* Smart account infrastructure
* Transaction execution system
* Capital management logic
* Risk controls
* Rebalancing schedule
And you consume Giza's:
* Optimization intelligence
* Optimal allocation calculations
* APR improvement metrics
* Action plans
* Execution-ready calldata
The Optimizer is **completely stateless** -- no data stored, no side effects. Each call is independent, which makes it straightforward to integrate with existing systems.
## When to Use IaaS
**Choose IaaS if:**
* You already have smart account infrastructure or Vaults
* You want to control transaction execution
* You need custom rebalancing schedules or strategies
* You're plugging into existing capital management systems
* You want optimization without autonomous execution
## Flow
1. You call Giza Optimizer with current allocations
2. Giza returns optimal allocations + action plan
3. You decide whether/when to execute
4. You execute transactions with your infrastructure
5. Repeat on your schedule
## The Optimizer Service
### What You Send
```typescript theme={null}
{
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Token you're optimizing
capital: '1000000000', // Your total capital
currentAllocations: { // Current state
aave: '500000000',
compound: '500000000'
},
protocols: ['aave', 'compound', 'moonwell'], // Protocols to consider
constraints: [...] // Optional constraints
}
```
### What You Get
```typescript theme={null}
{
optimization_result: {
allocations: [ // Optimal target allocation
{ protocol: "moonwell", allocation: "450000000", apr: 8.5 },
{ protocol: "aave", allocation: "350000000", apr: 7.2 },
{ protocol: "compound", allocation: "200000000", apr: 6.8 }
],
weighted_apr_initial: 7.0, // Before optimization
weighted_apr_final: 7.8, // After optimization
apr_improvement: 0.8, // +0.8% improvement
total_costs: 0.45 // Estimated gas costs (USD)
},
action_plan: [ // Step-by-step actions
{ action_type: "withdraw", protocol: "compound", amount: "300000000" },
{ action_type: "deposit", protocol: "moonwell", amount: "450000000" }
],
calldata: [ // Ready-to-execute transaction data
{
contract_address: "0x...",
function_name: "withdraw",
parameters: [...],
description: "Withdraw 300 USDC from Compound"
}
]
}
```
## Integration Example
```typescript theme={null}
import { Giza, Chain, WalletConstraints } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
async function getOptimalAllocation() {
// Call optimizer
const result = await giza.optimize({
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
capital: '1000000000',
currentAllocations: {
aave: '600000000',
compound: '400000000'
},
protocols: ['aave', 'compound', 'moonwell', 'seamless'],
constraints: [
{
kind: WalletConstraints.MIN_PROTOCOLS,
params: { min_protocols: 2 }
}
]
});
console.log(`APR improvement: +${result.optimization_result.apr_improvement}%`);
// Decide whether to execute based on YOUR logic
if (result.optimization_result.apr_improvement > 0.5) {
// Execute with YOUR infrastructure
await executeRebalancing(result.action_plan, result.calldata);
} else {
console.log('APR improvement too small, skip rebalancing');
}
}
async function executeRebalancing(actionPlan, calldata) {
// YOUR execution logic here
for (const call of calldata) {
await yourSmartAccount.executeTransaction({
to: call.contract_address,
data: encodeFunctionData(call.function_name, call.parameters)
});
}
}
```
## Optimizer Input/Output Reference
For the full optimizer response types including `OptimizationResult`, `ActionDetail`, and `CalldataInfo` interfaces, see the [SDK Optimizer Reference](/sdk-reference/optimizer).
For constraint types (`MIN_PROTOCOLS`, `MAX_AMOUNT_PER_PROTOCOL`, etc.), see [Constraints](/developers/architecture/constraints).
## Next Steps
Complete API documentation
Understand the optimization engine
All constraint types for controlling optimization
Full agentic integration tutorial
# Quickstart
Source: https://docs.gizatech.xyz/developers/quickstart
Install the SDK, create a smart account, and activate an agent
## Overview
This guide walks through the Giza Agent SDK from installation to a running agent. You'll create a smart account, activate an agent, and start yield optimization.
This quickstart focuses on the **Agentic integration** -- Giza handles smart accounts, execution, gas, and optimization. If you have your own execution infrastructure and just want optimization intelligence, see the [IaaS Integration Guide](/developers/guides/iaas-integration).
## What Giza Manages vs What You Build
| Giza manages | You build |
| -------------------------------- | -------------------- |
| Smart account creation (ZeroDev) | User interface |
| Session key management | Deposit flow |
| Transaction execution | Performance display |
| Gas payment | Withdrawal requests |
| Continuous optimization | Notification systems |
| Protocol rebalancing | User authentication |
## Architecture
```mermaid theme={null}
graph TB
A[Your Application] --> B[Giza Agent SDK]
B --> C[Giza Backend API]
C --> D[Agent Service]
D --> E[Smart Account]
E --> F1[Aave]
E --> F2[Compound]
E --> F3[Moonwell]
E --> F4[Other Protocols]
G[User] -->|Deposit| E
G -->|Monitor| A
A -->|Performance Data| G
```
## Prerequisites
Check your version: `node --version`
Download from [nodejs.org](https://nodejs.org/) if needed.
The SDK is built for TypeScript. JavaScript works too, but without type safety.
You'll need:
* `GIZA_API_KEY` - Your partner API key
* `GIZA_API_URL` - Giza backend URL
* `GIZA_PARTNER_NAME` - Your partner identifier
Request API keys from Giza teams.
## Installation
```bash npm theme={null}
npm install @gizatech/agent-sdk
```
```bash bun theme={null}
bun add @gizatech/agent-sdk
```
```bash yarn theme={null}
yarn add @gizatech/agent-sdk
```
## Environment Setup
Create a `.env` file in your project root:
```bash .env theme={null}
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
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
// Initialize once, reuse throughout your app
const giza = new Giza({
chain: 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.
```typescript theme={null}
async function onboardUser(userWallet: `0x${string}`) {
const agent = await giza.createAgent(userWallet);
console.log('Smart Account:', agent.wallet);
console.log('Deposit funds to this address');
return agent;
}
```
The smart account address is **deterministic** - calling `giza.createAgent` with the same EOA always returns the same address.
### Step 3: Get Available Protocols
Check which DeFi protocols are available for the token you want to optimize:
```typescript theme={null}
const USDC_BASE = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const { protocols } = await giza.protocols(USDC_BASE);
console.log('Available protocols:', protocols);
// ['aave', 'compound', 'moonwell', 'fluid', ...]
```
### Step 4: User Deposits Funds
User transfers USDC (or supported token) to the `agent.wallet` address from Step 2.
Wait for the transaction to be confirmed on-chain.
```typescript theme={null}
// Example: User deposits via your UI
const depositTxHash = await userWallet.sendTransaction({
to: agent.wallet,
value: parseUnits('1000', 6), // 1000 USDC (6 decimals)
});
```
### Step 5: Activate the Agent
After the user deposits, activate the agent to start optimization:
```typescript theme={null}
await agent.activate({
owner: userWallet,
token: USDC_BASE,
protocols: ['aave', 'compound', 'moonwell'],
txHash: depositTxHash,
constraints: [
{
kind: 'min_protocols',
params: { min_protocols: 2 } // Always diversify
}
]
});
```
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:
```typescript theme={null}
// Get current portfolio status
const info = await agent.portfolio();
console.log('Status:', info.status);
// Get APR
const { apr } = await agent.apr();
console.log(`Current APR: ${apr.toFixed(2)}%`);
// Get performance history
const { performance } = await agent.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:
```typescript theme={null}
// Withdraw everything and deactivate agent
await agent.withdraw();
// Wait for completion
await agent.waitForDeactivation({
interval: 5000,
timeout: 300000,
onUpdate: (status) => console.log('Status:', status),
});
```
```typescript theme={null}
// Withdraw specific amount, agent stays active
await agent.withdraw('500000000'); // 500 USDC (6 decimals)
// Agent continues optimizing remaining balance
```
## Additional Operations
### Top-Up Active Agent
```typescript theme={null}
await agent.topUp(newDepositTxHash);
```
### Update Protocols
```typescript theme={null}
await agent.updateProtocols(['aave', 'compound', 'moonwell', 'fluid']);
```
### Manual Rebalance
```typescript theme={null}
await agent.run();
```
## Multi-Chain Management
Run agents on multiple chains simultaneously:
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const baseGiza = new Giza({ chain: Chain.BASE });
const arbGiza = new Giza({ chain: Chain.ARBITRUM });
const baseAgent = await baseGiza.createAgent(userWallet);
const arbAgent = await arbGiza.createAgent(userWallet);
const [baseApr, arbApr] = await Promise.all([
baseAgent.apr(),
arbAgent.apr(),
]);
console.log('Base APR:', baseApr.apr);
console.log('Arbitrum APR:', arbApr.apr);
```
## Constraint-Based Risk Management
Use [constraints](/developers/architecture/constraints) to control agent behavior:
```typescript theme={null}
await agent.activate({
owner: userWallet,
token: USDC,
protocols: ['aave', 'compound', 'moonwell', 'fluid'],
txHash: depositTxHash,
constraints: [
// Diversify across at least 3 protocols
{ kind: 'min_protocols', params: { min_protocols: 3 } },
// Cap newer protocol at 30%
{
kind: 'max_amount_per_protocol',
params: { protocol: 'fluid', max_ratio: 0.3 },
},
// No dust allocations
{ kind: 'min_amount', params: { min_amount: '100000000' } },
],
});
```
## Error Handling
Wrap SDK calls in try-catch blocks:
```typescript theme={null}
import { ValidationError, GizaAPIError, TimeoutError } from '@gizatech/agent-sdk';
try {
const agent = await giza.createAgent(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 types, retry patterns, and user-friendly messages
## Next Steps
Understand smart accounts, agents, and protocols
Explore all SDK methods
HTTP API documentation
Use Optimizer with your own infrastructure
# Troubleshooting
Source: https://docs.gizatech.xyz/developers/troubleshooting
Common issues and solutions
## Installation Issues
### Package Not Found
```bash theme={null}
# Try clearing cache
rm -rf node_modules package-lock.json
npm cache clean --force
npm install @gizatech/agent-sdk
```
### Type Errors
Ensure you have TypeScript installed:
```bash theme={null}
npm install -D typescript @types/node
```
## Configuration Issues
### Environment Variables Not Found
```
Error: GIZA_API_KEY environment variable is required
```
**Solution:**
1. Create `.env` file in project root
2. Add required variables:
```bash theme={null}
GIZA_API_KEY=your-api-key
GIZA_API_URL=https://api.giza.tech
GIZA_PARTNER_NAME=your-name
```
3. Load with `dotenv`:
```typescript theme={null}
import 'dotenv/config';
```
### Invalid API Credentials
```
GizaAPIError: Unauthorized (401)
```
**Solution:**
* Verify `GIZA_API_KEY` is correct
* Check `GIZA_PARTNER_NAME` matches your registration
* Ensure `GIZA_API_URL` is correct
* Contact Giza support to verify credentials
## Smart Account Issues
### Invalid Address Format
```
ValidationError: wallet address must be a valid Ethereum address
```
**Solution:**
* Address must start with `0x`
* Must be 42 characters (0x + 40 hex chars)
* Use lowercase or checksum format
* Verify no extra spaces or characters
### Smart Account Not Found
```
GizaAPIError: Smart account not found (404)
```
**Solution:**
1. Create smart account first with `giza.createAgent(eoa)`
2. Verify you're using correct EOA wallet
3. Check you're querying correct chain
## Activation Issues
### No Deposits Found
```
GizaAPIError: No deposits detected in smart account
```
**Solution:**
1. Verify user deposited funds
2. Check transaction is confirmed on-chain
3. Ensure deposited to correct smart account address
4. Verify on correct chain
### Protocol Not Available
```
GizaAPIError: Protocol "xyz" not available for token
```
**Solution:**
1. Use `giza.protocols(token)` to check available protocols
2. Ensure protocol name is spelled correctly
3. Verify protocol supports your token
4. Check protocol is active on your chain
### Activation Timeout
**Solution:**
1. Increase timeout in SDK config:
```typescript theme={null}
const giza = new Giza({
chain: Chain.BASE,
timeout: 60000 // 60 seconds
});
```
2. Check network connectivity
3. Verify backend API is reachable
## Performance Issues
### Slow API Responses
**Solution:**
* Check your network connection
* Try increasing timeout
* Enable retry for better reliability:
```typescript theme={null}
const giza = new Giza({
chain: Chain.BASE,
enableRetry: true
});
```
* Consider caching responses
### Rate Limiting
```
GizaAPIError: Too Many Requests (429)
```
**Solution:**
1. Implement exponential backoff
2. Cache responses when possible
3. Reduce API call frequency
4. Contact Giza for higher rate limits
## Withdrawal Issues
### Withdrawal Takes Too Long
**Solution:**
* Withdrawals can take 5-15 minutes
* Protocols may have withdrawal queues
* Network congestion affects speed
* Use `agent.waitForDeactivation()` to track progress
* If > 30 minutes, contact support
### Withdrawal Stuck in "Deactivating"
**Solution:**
1. Check agent status: `agent.status()`
2. Verify transactions on block explorer
3. Some protocols have withdrawal delays
4. Network congestion can slow processing
5. Contact support if stuck > 1 hour
## General Debugging
### Enable Debug Logging
```typescript theme={null}
// Log all API calls
const originalFetch = global.fetch;
global.fetch = async (...args) => {
console.log('API Call:', args[0]);
const response = await originalFetch(...args);
console.log('Response:', response.status);
return response;
};
```
### Check SDK Version
```bash theme={null}
npm list @gizatech/agent-sdk
```
Update to latest:
```bash theme={null}
npm update @gizatech/agent-sdk
```
### Verify Chain
```typescript theme={null}
console.log('Chain:', giza.getChain());
console.log('API URL:', giza.getApiUrl());
```
## Getting Help
If issues persist:
1. **Check Documentation**: Review relevant docs sections
2. **Search Issues**: Check GitHub issues for similar problems
3. **Enable Retry**: Try with `enableRetry: true`
4. **Collect Info**:
* SDK version
* Node version
* Error messages
* Steps to reproduce
5. **Contact Support**:
* Email: [support@gizatech.xyz](mailto:support@gizatech.xyz)
* GitHub: Open an issue
* Discord: Join community
## Common Error Reference
| Error Code | Meaning | Common Cause |
| ---------- | ------------------- | ---------------------- |
| 400 | Bad Request | Invalid parameters |
| 401 | Unauthorized | Wrong API credentials |
| 404 | Not Found | Resource doesn't exist |
| 429 | Rate Limited | Too many requests |
| 500 | Server Error | Backend issue, retry |
| 503 | Service Unavailable | Temporary outage |
## Smart Account Issues (Additional)
### Smart Account Creation Fails
Check:
* Origin wallet is a valid Ethereum address (0x + 40 hex chars)
* Chain is supported
* API credentials are correct
### Can't Find Existing Smart Account
Make sure:
* You're using the same EOA as when it was created
* You're querying the correct chain
* The smart account was actually created (check blockchain explorer)
### Deposits Not Showing Up
Verify:
* Transaction was sent to the correct `smartAccountAddress`
* Transaction confirmed on-chain (check explorer)
* You're checking the right chain
* Agent was activated after deposit
## Avoiding Issues
1. Validate inputs before SDK calls
2. Use try-catch for error handling
3. Add retry logic for network issues
4. Cache responses where it makes sense
5. Monitor API health in production
6. Keep the SDK up to date
7. Test on testnet before production
8. Handle timeouts
# Giza Documentation
Source: https://docs.gizatech.xyz/introduction
Agents for on-chain capital
## Use the Giza App
Connect your wallet and activate your first agent
Monitor performance, deposit, and withdraw
Fee structure and the Giza Rewards program
## Use Giza with AI Agents
Manage your yield through chat
Add Giza tools to your coding assistant
Use Giza with Openclaw's AI assistant
## Build with Giza
Install the SDK and activate your first agent
TypeScript SDK documentation
REST API endpoints
Smart accounts, agents, protocols, and optimization
Use the optimizer with your own execution
## Resources
Common issues and solutions
Error types and retry patterns
Source code
# Lifecycle
Source: https://docs.gizatech.xyz/sdk-reference/agent/lifecycle
Activate, deactivate, top up, and run yield agents
## Overview
Lifecycle methods manage the agent's operational state. An agent transitions through several states from creation to deactivation. All methods in this section are called on an [`Agent`](/sdk-reference/agent/overview) instance.
## State Diagram
The agent follows this state machine during its lifecycle:
```mermaid theme={null}
stateDiagram-v2
[*] --> Inactive
Inactive --> Activating: activate()
Activating --> Activated: success
Activating --> ActivationFailed: failure
ActivationFailed --> Activating: activate() retry
Activated --> Running: run()
Running --> Activated: run completes
Running --> RunFailed: run failure
RunFailed --> Activated: recovery
Activated --> Deactivating: deactivate()
Deactivating --> Deactivated: success
Deactivating --> DeactivationFailed: failure
Activated --> Blocked: policy violation
Activated --> Emergency: emergency stop
```
The `AgentStatus` enum maps to these states:
```typescript theme={null}
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',
}
```
## `activate(options)`
```typescript theme={null}
async activate(options: ActivateOptions): Promise
```
Activates the agent by registering the initial deposit, token, and protocol selection. Call this after the user has sent their deposit transaction.
### Parameters
The EOA address that owns the smart account.
The deposit token address (e.g., USDC).
List of protocol names the agent should allocate to. Must contain at least one protocol.
The transaction hash of the user's deposit into the smart account.
Optional allocation constraints (min/max amounts per protocol, excluded protocols).
### Return Type
```typescript theme={null}
interface ActivateResponse {
message: string;
wallet: string;
}
```
### Example
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = await giza.createAgent('0xUserEOA...');
const result = await agent.activate({
owner: '0xUserEOA...',
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
protocols: ['aave', 'compound', 'moonwell'],
txHash: '0xDepositTransactionHash...',
});
console.log(result.message); // 'Agent activated successfully'
console.log(result.wallet); // smart account address
```
### Activation with Constraints
```typescript theme={null}
await agent.activate({
owner: '0xUserEOA...',
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
protocols: ['aave', 'compound', 'moonwell'],
txHash: '0xDepositTxHash...',
constraints: [
{
kind: 'max_allocation_amount_per_protocol',
params: { protocol: 'aave', amount: '500000000' },
},
{
kind: 'exclude_protocol',
params: { protocol: 'euler' },
},
],
});
```
***
## `deactivate(options?)`
```typescript theme={null}
async deactivate(options?: DeactivateOptions): Promise
```
Deactivates the agent and optionally transfers remaining funds back to the owner. The agent withdraws from all protocols before deactivating.
### Parameters
Whether to transfer funds back to the owner's EOA. Defaults to `true`.
### Return Type
```typescript theme={null}
interface DeactivateResponse {
message: string;
}
```
### Example
```typescript theme={null}
// Deactivate and transfer funds back (default)
const result = await agent.deactivate();
console.log(result.message);
// Deactivate but keep funds in the smart account
const result2 = await agent.deactivate({ transfer: false });
```
Deactivation is asynchronous. The agent enters the `DEACTIVATING` state and may take time to withdraw from all protocols. Use `agent.waitForDeactivation()` to poll until the process completes.
***
## `topUp(txHash)`
```typescript theme={null}
async topUp(txHash: string): Promise
```
Records an additional deposit into an already-active agent. Call this after the user sends a follow-up deposit transaction to the smart account.
### Parameters
The transaction hash of the additional deposit.
### Return Type
```typescript theme={null}
interface TopUpResponse {
message: string;
}
```
### Example
```typescript theme={null}
const result = await agent.topUp('0xAdditionalDepositTxHash...');
console.log(result.message);
```
The agent must be in the `ACTIVATED` state to accept a top-up. If the agent is deactivating or deactivated, the call will fail.
***
## `run()`
```typescript theme={null}
async run(): Promise
```
Triggers a manual optimization run. The agent evaluates current protocol yields and rebalances allocations if a better distribution is found.
### Return Type
```typescript theme={null}
interface RunResponse {
status: string;
}
```
### Example
```typescript theme={null}
const result = await agent.run();
console.log('Run status:', result.status);
```
Agents also run automatically on a schedule. Use `run()` when you want to trigger an immediate rebalancing, for example after market conditions change.
## Complete Lifecycle Example
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
// 1. Create agent
const agent = await giza.createAgent('0xUserEOA...');
// 2. Activate after user deposits
await agent.activate({
owner: '0xUserEOA...',
token: USDC,
protocols: ['aave', 'compound'],
txHash: '0xInitialDepositTx...',
});
// 3. Top up with additional deposit
await agent.topUp('0xSecondDepositTx...');
// 4. Trigger a manual run
await agent.run();
// 5. Monitor status
const info = await agent.portfolio();
console.log('Status:', info.status);
// 6. Deactivate when done
await agent.deactivate();
// 7. Wait for deactivation to complete
const final = await agent.waitForDeactivation({
interval: 10000, // poll every 10 seconds
timeout: 300000, // give up after 5 minutes
onUpdate: (status) => console.log('Status:', status),
});
console.log('Final status:', final.status);
```
## Next Steps
Track portfolio value, APR, and performance history
All Agent methods at a glance
# Monitoring
Source: https://docs.gizatech.xyz/sdk-reference/agent/monitoring
Track portfolio value, performance history, APR, and deposits
## Overview
Monitoring methods let you inspect the current state of an agent and its historical performance. All methods are called on an [`Agent`](/sdk-reference/agent/overview) instance and are scoped to that agent's smart-account wallet.
## `portfolio()`
```typescript theme={null}
async portfolio(): Promise
```
Returns the full current state of the agent, including deposits, withdrawals, status, protocol selection, and key dates.
### Return Type
```typescript theme={null}
interface AgentInfo {
wallet: Address;
deposits: Deposit[];
withdraws?: Withdraw[];
status: AgentStatus;
activation_date: string;
last_deactivation_date?: string;
last_reactivation_date?: string;
selected_protocols: string[];
current_protocols?: string[];
current_token?: string;
eoa?: Address;
}
```
### Example
```typescript theme={null}
const info = await agent.portfolio();
console.log('Wallet:', info.wallet);
console.log('Status:', info.status);
console.log('Protocols:', info.selected_protocols.join(', '));
console.log('Activated:', info.activation_date);
for (const deposit of info.deposits) {
console.log(`Deposit: ${deposit.amount} ${deposit.token_type}`);
}
```
***
## `performance(options?)`
```typescript theme={null}
async performance(
options?: PerformanceOptions
): Promise
```
Returns historical performance data points for charting portfolio value over time. Each data point includes the date, value, USD value, accrued rewards, and portfolio breakdown.
### Parameters
ISO date string to filter performance data from this date onward. Omit to get all available history.
### Return Type
```typescript theme={null}
interface PerformanceChartResponse {
performance: PerformanceData[];
}
interface PerformanceData {
date: string;
value: number;
value_in_usd?: number;
accrued_rewards?: AccruedRewardsBySymbol;
portfolio?: Portfolio;
agent_token_amount?: number;
}
```
Where `Portfolio` is `Record` mapping protocol names to their allocation details, and `AccruedRewardsBySymbol` is `Record` mapping reward token symbols to their locked/unlocked amounts.
### Example
```typescript theme={null}
// Get all performance history
const { performance } = await agent.performance();
for (const point of performance) {
console.log(`${point.date}: $${point.value_in_usd}`);
}
// Get performance from a specific date
const { performance: recent } = await agent.performance({
from: '2025-01-01',
});
```
***
## `apr(options?)`
```typescript theme={null}
async apr(options?: AprOptions): Promise
```
Returns the agent's annualized percentage rate (APR). Optionally specify a date range to compute APR over a specific period. The response can include sub-period breakdowns for detailed analysis.
### Parameters
ISO date string for the start of the APR calculation period.
ISO date string for the end of the APR calculation period.
When `true`, uses the exact end date instead of rounding to the nearest period boundary.
### Return Type
```typescript theme={null}
interface WalletAprResponse {
apr: number;
sub_periods?: WalletAprSubPeriod[];
}
interface WalletAprSubPeriod {
start_date: string;
end_date: string;
return_: number;
initial_value: number;
}
```
### Example
```typescript theme={null}
// Get overall APR
const { apr } = await agent.apr();
console.log(`APR: ${apr}%`);
// Get APR for a specific date range
const result = await agent.apr({
startDate: '2025-01-01',
endDate: '2025-06-01',
});
console.log(`Period APR: ${result.apr}%`);
if (result.sub_periods) {
for (const period of result.sub_periods) {
console.log(
` ${period.start_date} to ${period.end_date}: ` +
`return=${period.return_}, initial=${period.initial_value}`
);
}
}
```
***
## `aprByTokens(period?)`
```typescript theme={null}
async aprByTokens(period?: Period): Promise
```
Returns APR data broken down by token allocation. Each entry includes the current value, USD value, and base/total APR for that allocation.
### Parameters
Time period for the APR calculation. Use `Period.ALL` for the entire history or `Period.DAY` for daily.
```typescript theme={null}
enum Period {
ALL = 'all',
DAY = 'day',
}
```
### Return Type
```typescript theme={null}
type AprByTokenResponse = AllocatedValue[];
interface AllocatedValue {
value: number;
value_in_usd: number;
base_apr?: number;
total_apr?: number;
}
```
### Example
```typescript theme={null}
import { Period } from '@gizatech/agent-sdk';
const allocations = await agent.aprByTokens(Period.ALL);
for (const alloc of allocations) {
console.log(
`Value: ${alloc.value} ($${alloc.value_in_usd}), ` +
`Base APR: ${alloc.base_apr}%, Total APR: ${alloc.total_apr}%`
);
}
```
***
## `deposits()`
```typescript theme={null}
async deposits(): Promise
```
Returns all deposits made to the agent's smart account.
### Return Type
```typescript theme={null}
interface DepositListResponse {
deposits: Deposit[];
}
interface Deposit {
amount: number;
token_type: string;
date?: string;
tx_hash?: string;
block_number?: number;
}
```
### Example
```typescript theme={null}
const { deposits } = await agent.deposits();
let total = 0;
for (const deposit of deposits) {
console.log(
`${deposit.date}: ${deposit.amount} ${deposit.token_type} ` +
`(tx: ${deposit.tx_hash})`
);
total += deposit.amount;
}
console.log(`Total deposited: ${total}`);
```
***
## Building a Dashboard
This example shows how to combine monitoring methods to build a portfolio dashboard view.
```typescript theme={null}
import { Giza, Chain, Period } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = await giza.getAgent('0xUserEOA...');
// Fetch all data in parallel
const [info, perf, aprData, tokenAprs, depositList] =
await Promise.all([
agent.portfolio(),
agent.performance({ from: '2025-01-01' }),
agent.apr(),
agent.aprByTokens(Period.ALL),
agent.deposits(),
]);
// Agent overview
console.log('=== Agent Dashboard ===');
console.log(`Wallet: ${info.wallet}`);
console.log(`Status: ${info.status}`);
console.log(`Active since: ${info.activation_date}`);
console.log(`Protocols: ${info.selected_protocols.join(', ')}`);
// APR summary
console.log(`\nOverall APR: ${aprData.apr}%`);
// Token allocation breakdown
console.log('\n--- Allocation Breakdown ---');
for (const alloc of tokenAprs) {
console.log(
` Value: $${alloc.value_in_usd.toFixed(2)} | ` +
`Base APR: ${alloc.base_apr?.toFixed(2)}% | ` +
`Total APR: ${alloc.total_apr?.toFixed(2)}%`
);
}
// Recent performance (last 5 data points)
console.log('\n--- Recent Performance ---');
const recent = perf.performance.slice(-5);
for (const point of recent) {
console.log(` ${point.date}: $${point.value_in_usd?.toFixed(2)}`);
}
// Deposit history
console.log('\n--- Deposits ---');
for (const dep of depositList.deposits) {
console.log(
` ${dep.date}: ${dep.amount} ${dep.token_type}`
);
}
```
Use `Promise.all` to fetch independent data in parallel. This reduces total latency compared to sequential calls.
## Next Steps
Activation, deactivation, and agent state management
All Agent methods at a glance
Chain-level queries and agent factory methods
# Agent Class
Source: https://docs.gizatech.xyz/sdk-reference/agent/overview
Wallet-scoped handle for managing an autonomous yield agent
## What Is an Agent
An `Agent` is a resource handle bound to a single smart-account wallet address. Every method on the `Agent` class operates on that wallet, so you never need to pass the address repeatedly. The `Agent` encapsulates the full lifecycle of an autonomous yield agent: activation, monitoring, withdrawals, rewards, and protocol management.
## How to Get One
There are three ways to obtain an `Agent` instance, all through the [`Giza`](/sdk-reference/giza) client:
| Method | API Call | Use Case |
| ----------------------- | -------- | ---------------------------------------- |
| `giza.createAgent(eoa)` | Yes | Create a new smart account for an EOA |
| `giza.getAgent(eoa)` | Yes | Look up an existing smart account by EOA |
| `giza.agent(wallet)` | No | Wrap a known smart-account address |
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
// Option 1: Create a new smart account
const agent = await giza.createAgent('0xUserEOA...');
console.log('New smart account:', agent.wallet);
// Option 2: Retrieve an existing smart account
const existing = await giza.getAgent('0xUserEOA...');
console.log('Existing smart account:', existing.wallet);
// Option 3: Wrap a known address (no API call)
const direct = giza.agent('0xSmartAccountAddress...');
```
## The `wallet` Property
Every `Agent` exposes the smart-account address it is bound to:
```typescript theme={null}
readonly wallet: Address // `0x${string}`
```
This is the address used in all API calls made by the agent. It is set at construction time and cannot be changed.
## Method Categories
The `Agent` class groups its methods into six categories. Each is documented on its own page.
### Lifecycle
Manage the agent's activation state and trigger runs.
| Method | Return Type | Description |
| ---------------------- | -------------------- | -------------------------------------------------------- |
| `activate(options)` | `ActivateResponse` | Activate the agent with token, protocols, and deposit tx |
| `deactivate(options?)` | `DeactivateResponse` | Deactivate and optionally transfer funds back |
| `topUp(txHash)` | `TopUpResponse` | Record an additional deposit |
| `run()` | `RunResponse` | Trigger a manual optimization run |
Full method reference with parameters, types, and examples
### Monitoring
Track portfolio value, performance history, and APR.
| Method | Return Type | Description |
| ----------------------- | -------------------------- | ---------------------------------------------- |
| `portfolio()` | `AgentInfo` | Current portfolio state, deposits, status |
| `performance(options?)` | `PerformanceChartResponse` | Historical performance data points |
| `apr(options?)` | `WalletAprResponse` | Current APR with optional sub-period breakdown |
| `aprByTokens(period?)` | `AprByTokenResponse` | APR broken down by token allocation |
| `deposits()` | `DepositListResponse` | List of all deposits |
Full method reference with parameters, types, and examples
### Transactions
Browse transaction history, execution records, and logs. These methods return a `Paginator` for async iteration.
| Method | Return Type | Description |
| -------------------------------------- | ----------------------------------------- | ----------------------------------- |
| `transactions(options?)` | `Paginator` | All wallet transactions |
| `executions(options?)` | `Paginator` | Execution batches with transactions |
| `executionLogs(executionId, options?)` | `Paginator` | Logs for a specific execution |
| `logs(options?)` | `Paginator` | All wallet logs |
### Withdrawals
Withdraw funds and monitor withdrawal status.
| Method | Return Type | Description |
| ------------------------------- | -------------------------- | ------------------------------------- |
| `withdraw(amount?)` | `WithdrawResponse` | Initiate a partial or full withdrawal |
| `status()` | `WithdrawalStatusResponse` | Current agent status and dates |
| `waitForDeactivation(options?)` | `WithdrawalStatusResponse` | Poll until deactivation completes |
| `fees()` | `FeeResponse` | Current fee structure |
| `limit(eoa)` | `LimitResponse` | Withdrawal limit for the EOA |
### Rewards
Claim and inspect accrued rewards. Paginated history uses the `Paginator` class.
| Method | Return Type | Description |
| ------------------------- | ------------------------ | --------------------------- |
| `claimRewards()` | `ClaimedRewardsResponse` | Claim all available rewards |
| `rewards(options?)` | `Paginator` | Paginated reward records |
| `rewardHistory(options?)` | `Paginator` | Paginated reward history |
### Protocols
View and update the agent's protocol selection and constraints.
| Method | Return Type | Description |
| -------------------------------- | -------------------- | -------------------------------------- |
| `protocols()` | `Protocol[]` | Current protocol list for the agent |
| `updateProtocols(protocols)` | `void` | Replace the agent's protocol selection |
| `constraints()` | `ConstraintConfig[]` | Current allocation constraints |
| `updateConstraints(constraints)` | `void` | Replace allocation constraints |
| `whitelist()` | `unknown` | Get the agent's whitelist |
## Next Steps
Activation, deactivation, top-ups, and runs
Portfolio, performance, APR, and deposits
Agent factory methods and chain-level queries
SDK architecture and configuration
# Protocols & Constraints
Source: https://docs.gizatech.xyz/sdk-reference/agent/protocols
Manage protocol selection, allocation constraints, and whitelist for an agent
## Overview
The Agent class provides methods for managing which DeFi protocols an agent can allocate to and what constraints govern those allocations. These are wallet-scoped operations that apply to a specific smart account.
There are two levels of protocol queries in the SDK:
* **`giza.protocols(token)`** -- Chain-level query on the `Giza` client. Returns active protocol names for a given token across the chain.
* **`agent.protocols()`** -- Wallet-scoped query on the `Agent` instance. Returns full `Protocol` objects configured for this specific agent.
***
## protocols()
Get the full list of protocols configured for this agent's smart account, including metadata like TVL, APR, and pool information.
### Signature
```typescript theme={null}
protocols(): Promise
```
### Returns
`Promise`
### Protocol Type
```typescript theme={null}
interface Protocol {
name: string;
is_active: boolean;
description: string;
tvl: number;
apr: number | null;
pools: ProtocolPool[] | null;
created_at: string;
updated_at: string | null;
chain_id: number;
parent_protocol: string;
link: string;
address: string | null;
agent_token: string | null;
title: string | null;
}
interface ProtocolPool {
name: string;
apy: number;
}
```
### Examples
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
const protocols = await agent.protocols();
for (const protocol of protocols) {
console.log(`${protocol.name} (active: ${protocol.is_active})`);
console.log(` TVL: $${protocol.tvl}`);
console.log(` APR: ${protocol.apr ?? 'N/A'}%`);
if (protocol.pools) {
for (const pool of protocol.pools) {
console.log(` Pool: ${pool.name} - APY: ${pool.apy}%`);
}
}
}
```
***
## updateProtocols()
Update the list of protocols the agent is allowed to allocate to. At least one protocol must be provided.
### Signature
```typescript theme={null}
updateProtocols(protocols: string[]): Promise
```
### Parameters
Array of protocol names to enable for this agent. Must contain at least one entry.
### Errors
* **`ValidationError`**: Thrown if the protocols array is empty.
### Examples
```typescript theme={null}
// Update to use Aave and Morpho
await agent.updateProtocols(['aave', 'morpho']);
// Verify the update
const updated = await agent.protocols();
const activeNames = updated
.filter((p) => p.is_active)
.map((p) => p.name);
console.log('Active protocols:', activeNames);
```
***
## constraints()
Get the current allocation constraints for this agent.
### Signature
```typescript theme={null}
constraints(): Promise
```
### Returns
`Promise`
### ConstraintConfig Type
```typescript theme={null}
interface ConstraintConfig {
kind: string;
params: Record;
}
```
The `kind` field corresponds to one of the constraint types. Common constraint kinds include:
| Kind | Description | Params |
| ------------------------------------ | ---------------------------------------------- | ---------------------------- |
| `min_protocols` | Minimum number of protocols to allocate across | `{ min_protocols: number }` |
| `max_allocation_amount_per_protocol` | Maximum percentage per protocol | `{ max_allocation: number }` |
| `max_amount_per_protocol` | Maximum absolute amount per protocol | `{ max_amount: number }` |
| `min_amount` | Minimum allocation amount | `{ min_amount: number }` |
| `exclude_protocol` | Exclude a protocol from allocation | `{ protocol: string }` |
| `min_allocation_amount_per_protocol` | Minimum allocation per protocol | `{ min_allocation: number }` |
### Examples
```typescript theme={null}
const constraints = await agent.constraints();
for (const constraint of constraints) {
console.log(`${constraint.kind}:`, constraint.params);
}
```
***
## updateConstraints()
Replace the allocation constraints for this agent.
### Signature
```typescript theme={null}
updateConstraints(constraints: ConstraintConfig[]): Promise
```
### Parameters
Array of constraint configurations to apply to the agent.
### Examples
```typescript theme={null}
await agent.updateConstraints([
{
kind: 'max_allocation_amount_per_protocol',
params: { max_allocation: 50 },
},
{
kind: 'min_protocols',
params: { min_protocols: 2 },
},
{
kind: 'exclude_protocol',
params: { protocol: 'compound' },
},
]);
// Verify
const updated = await agent.constraints();
console.log('Constraints:', updated);
```
***
## whitelist()
Get the whitelist configuration for this agent's smart account.
### Signature
```typescript theme={null}
whitelist(): Promise
```
### Returns
`Promise` -- the whitelist data structure varies by configuration.
### Examples
```typescript theme={null}
const wl = await agent.whitelist();
console.log('Whitelist:', wl);
```
***
## Chain-Level vs. Wallet-Scoped Protocols
The SDK provides protocol queries at two levels. Here is how they differ:
```typescript Chain-level (Giza client) theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
// Returns active protocol names for USDC on Base
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const { protocols } = await giza.protocols(USDC);
console.log(protocols); // ['aave', 'morpho', 'moonwell', ...]
```
```typescript Wallet-scoped (Agent instance) theme={null}
const agent = giza.agent('0xYourSmartAccountAddress');
// Returns full Protocol objects for this agent
const protocols = await agent.protocols();
for (const p of protocols) {
console.log(p.name, p.tvl, p.apr);
}
```
Use the chain-level query to discover available protocols for a token. Use the wallet-scoped query to inspect and manage the protocols configured for a specific agent.
# Rewards
Source: https://docs.gizatech.xyz/sdk-reference/agent/rewards
Claim accrued rewards and browse reward history with pagination
## Overview
The Agent class provides methods for claiming accrued protocol rewards and browsing reward history. Reward queries return [`Paginator`](/sdk-reference/paginator) instances for efficient iteration over potentially large result sets.
***
## claimRewards()
Claim all accrued rewards for the agent's smart account. This triggers an on-chain claim of rewards accumulated from the protocols the agent is allocated to.
### Signature
```typescript theme={null}
claimRewards(): Promise
```
### Returns
`Promise`
### Response Types
```typescript theme={null}
interface ClaimedRewardsResponse {
rewards: ClaimedReward[];
}
interface ClaimedReward {
token: string;
amount: number;
amount_float: number;
current_price_in_underlying: number;
}
```
### Examples
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
const claimed = await agent.claimRewards();
for (const reward of claimed.rewards) {
console.log(`Token: ${reward.token}`);
console.log(` Amount: ${reward.amount_float}`);
console.log(` Value in underlying: ${reward.current_price_in_underlying}`);
}
```
***
## rewards()
Returns a paginator over the agent's current reward records.
### Signature
```typescript theme={null}
rewards(options?: PaginationOptions): Paginator
```
### Parameters
Optional pagination and sorting configuration.
Items per page. Defaults to `20`.
Sort order. Use `SortOrder.DATE_ASC` or `SortOrder.DATE_DESC`.
### Returns
`Paginator`
### RewardDTO Type
```typescript theme={null}
interface RewardDTO {
user_id: string;
base_apr: number;
extra_apr: number;
ticker: string;
reward_amount: number;
group: string;
transaction_hash: string;
start_date: string;
end_date: string;
id: string;
created_at: string;
updated_at: string;
}
```
### Examples
```typescript Async iteration theme={null}
import { SortOrder } from '@gizatech/agent-sdk';
for await (const reward of agent.rewards({ sort: SortOrder.DATE_DESC })) {
console.log(`${reward.ticker}: ${reward.reward_amount}`);
console.log(` APR: ${reward.base_apr}% + ${reward.extra_apr}% extra`);
console.log(` Period: ${reward.start_date} to ${reward.end_date}`);
}
```
```typescript First N items theme={null}
const topRewards = await agent.rewards({
sort: SortOrder.DATE_DESC,
}).first(5);
for (const reward of topRewards) {
console.log(`${reward.ticker}: ${reward.reward_amount}`);
}
```
```typescript Specific page theme={null}
const page = await agent.rewards().page(1, { limit: 10 });
console.log(`Total rewards: ${page.total}`);
for (const reward of page.items) {
console.log(`${reward.ticker}: ${reward.reward_amount}`);
}
```
***
## rewardHistory()
Returns a paginator over the agent's historical reward records. This includes past claimed and distributed rewards.
### Signature
```typescript theme={null}
rewardHistory(options?: PaginationOptions): Paginator
```
### Parameters
Optional pagination and sorting configuration.
Items per page. Defaults to `20`.
Sort order. Use `SortOrder.DATE_ASC` or `SortOrder.DATE_DESC`.
### Returns
`Paginator`
### Examples
```typescript theme={null}
import { SortOrder } from '@gizatech/agent-sdk';
// Get the 10 most recent historical rewards
const history = await agent.rewardHistory({
sort: SortOrder.DATE_DESC,
}).first(10);
for (const reward of history) {
console.log(`${reward.start_date} - ${reward.end_date}`);
console.log(` ${reward.ticker}: ${reward.reward_amount}`);
console.log(` TX: ${reward.transaction_hash}`);
}
```
Both `rewards()` and `rewardHistory()` return [`Paginator`](/sdk-reference/paginator) instances. See the [Paginator reference](/sdk-reference/paginator) for the full iteration API.
# Transactions & Executions
Source: https://docs.gizatech.xyz/sdk-reference/agent/transactions
Paginated access to transaction history, execution records, and agent logs
## Overview
The Agent class provides paginated methods for querying transaction history, execution records, and logs. Each method returns a [`Paginator`](/sdk-reference/paginator) instance that supports async iteration, page-based access, and convenience helpers.
## transactions()
Returns a paginator over the agent's on-chain transactions, sorted by date.
### Signature
```typescript theme={null}
transactions(options?: PaginationOptions): Paginator
```
### Parameters
Optional pagination and sorting configuration.
Items per page. Defaults to `20`.
Sort order. Use `SortOrder.DATE_ASC` or `SortOrder.DATE_DESC`.
### Returns
`Paginator` -- an async-iterable paginator yielding `Transaction` objects.
### Transaction Type
```typescript theme={null}
interface Transaction {
action: TxAction;
date: string;
amount: number;
amount_out?: number;
token_type: string;
status: TxStatus;
transaction_hash?: string;
protocol?: string;
new_token?: string;
correlation_id?: string;
apr?: number;
block_number?: number;
}
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',
}
```
### Examples
```typescript Async iteration theme={null}
import { Giza, Chain, SortOrder } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
for await (const tx of agent.transactions({ sort: SortOrder.DATE_DESC })) {
console.log(tx.date, tx.action, tx.amount, tx.token_type);
}
```
```typescript First N items theme={null}
const recentTxs = await agent.transactions({
sort: SortOrder.DATE_DESC,
}).first(5);
for (const tx of recentTxs) {
console.log(`${tx.action}: ${tx.amount} ${tx.token_type}`);
}
```
```typescript Specific page theme={null}
const page2 = await agent.transactions().page(2, { limit: 25 });
console.log(`Page ${page2.page}, total: ${page2.total}`);
for (const tx of page2.items) {
console.log(tx.transaction_hash, tx.status);
}
```
***
## executions()
Returns a paginator over the agent's execution records. Each execution contains a list of transactions that were part of that run.
### Signature
```typescript theme={null}
executions(options?: PaginationOptions): Paginator
```
### Parameters
Optional pagination and sorting configuration.
Items per page. Defaults to `20`.
Sort order. Use `SortOrder.DATE_ASC` or `SortOrder.DATE_DESC`.
### Returns
`Paginator`
### ExecutionWithTransactionsDTO Type
```typescript theme={null}
interface ExecutionWithTransactionsDTO {
id: string;
execution_plan: unknown;
execution_type: string;
status: ExecutionStatus;
created_at: string;
transactions: Transaction[];
}
enum ExecutionStatus {
RUNNING = 'running',
FAILED = 'failed',
SUCCESS = 'success',
}
```
### Examples
```typescript theme={null}
const recentExecutions = await agent.executions({
sort: SortOrder.DATE_DESC,
}).first(10);
for (const exec of recentExecutions) {
console.log(`Execution ${exec.id}: ${exec.status}`);
console.log(` Type: ${exec.execution_type}`);
console.log(` Transactions: ${exec.transactions.length}`);
}
```
***
## executionLogs()
Returns a paginator over the logs for a specific execution.
### Signature
```typescript theme={null}
executionLogs(
executionId: string,
options?: PaginationOptions
): Paginator
```
### Parameters
The execution ID to fetch logs for.
Optional pagination configuration.
Items per page. Defaults to `20`.
### Returns
`Paginator`
### LogDTO Type
```typescript theme={null}
interface LogDTO {
type: string;
data: unknown;
}
```
### Examples
```typescript theme={null}
const executions = await agent.executions().first(1);
const latestExec = executions[0];
if (latestExec) {
for await (const log of agent.executionLogs(latestExec.id)) {
console.log(`[${log.type}]`, log.data);
}
}
```
***
## logs()
Returns a paginator over all logs for the agent, across all executions.
### Signature
```typescript theme={null}
logs(options?: PaginationOptions): Paginator
```
### Parameters
Optional pagination configuration.
Items per page. Defaults to `20`.
### Returns
`Paginator`
### Examples
```typescript theme={null}
const recentLogs = await agent.logs().first(50);
for (const log of recentLogs) {
console.log(`[${log.type}]`, JSON.stringify(log.data));
}
```
***
## PaginationOptions
All paginated methods accept the same options object.
```typescript theme={null}
interface PaginationOptions {
limit?: number;
sort?: string;
}
enum SortOrder {
DATE_ASC = 'date_asc',
DATE_DESC = 'date_desc',
}
```
All paginated methods return a [`Paginator`](/sdk-reference/paginator) instance. See the [Paginator reference](/sdk-reference/paginator) for the full API including async iteration, `.page()`, and `.first()`.
# Withdrawals
Source: https://docs.gizatech.xyz/sdk-reference/agent/withdrawals
Partial and full withdrawal operations, status polling, fees, and limits
## Overview
The Agent class provides methods for withdrawing funds, monitoring withdrawal status, and querying fees and limits. Withdrawals come in two forms:
* **Partial withdrawal**: Specify an amount to withdraw while the agent stays active.
* **Full withdrawal**: Omit the amount to deactivate the agent and transfer all funds back to the origin wallet.
***
## withdraw()
Initiate a withdrawal from the agent's smart account.
### Signature
```typescript theme={null}
withdraw(amount?: string): Promise
```
### Parameters
Token amount to withdraw, in the token's smallest unit (e.g., `'500000000'` for 500 USDC with 6 decimals). When omitted, the agent is fully deactivated and all funds are transferred to the origin wallet.
### Returns
`Promise` -- the response type depends on the withdrawal mode:
* **Full withdrawal** (no amount): Returns `FullWithdrawResponse` with a confirmation message. The agent begins deactivation.
* **Partial withdrawal** (amount provided): Returns `PartialWithdrawResponse` with details of the withdrawn tokens.
### Response Types
```typescript theme={null}
type WithdrawResponse =
| FullWithdrawResponse
| PartialWithdrawResponse;
interface FullWithdrawResponse {
message: string;
}
interface PartialWithdrawResponse {
date: string;
amount: number;
value: number;
withdraw_details: WithdrawDetail[];
}
interface WithdrawDetail {
token: string;
amount: string;
value: number;
value_in_usd: number;
principal_amount?: number;
yield_amount?: number;
fee_amount?: number;
tx_hash?: string;
block_number?: number;
}
```
### Examples
```typescript Partial withdrawal theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
// Withdraw 500 USDC (6 decimals)
const result = await agent.withdraw('500000000');
if ('withdraw_details' in result) {
for (const detail of result.withdraw_details) {
console.log(`${detail.token}: ${detail.amount}`);
console.log(` USD value: $${detail.value_in_usd}`);
console.log(` Principal: ${detail.principal_amount}`);
console.log(` Yield: ${detail.yield_amount}`);
}
}
```
```typescript Full withdrawal theme={null}
// Full withdrawal: deactivates agent and transfers all funds
const result = await agent.withdraw();
if ('message' in result) {
console.log(result.message);
}
// Poll until deactivation completes
const finalStatus = await agent.waitForDeactivation({
interval: 5000,
timeout: 300000,
onUpdate: (status) => {
console.log('Status:', status);
},
});
console.log('Deactivated:', finalStatus.status);
```
***
## status()
Get the current status of the agent, including activation and deactivation dates.
### Signature
```typescript theme={null}
status(): Promise
```
### Returns
`Promise`
### WithdrawalStatusResponse Type
```typescript theme={null}
interface WithdrawalStatusResponse {
status: AgentStatus;
wallet: Address;
activation_date: string;
last_deactivation_date?: string;
last_reactivation_date?: string;
}
```
### Examples
```typescript theme={null}
const info = await agent.status();
console.log('Status:', info.status);
console.log('Wallet:', info.wallet);
console.log('Activated:', info.activation_date);
if (info.last_deactivation_date) {
console.log('Last deactivated:', info.last_deactivation_date);
}
```
***
## waitForDeactivation()
Poll the agent status until it reaches `DEACTIVATED`. This is used after calling `withdraw()` without an amount (full withdrawal) to wait for the deactivation process to complete.
### Signature
```typescript theme={null}
waitForDeactivation(
options?: WaitForDeactivationOptions
): Promise
```
### Parameters
Polling configuration.
Polling interval in milliseconds. Defaults to `5000` (5 seconds). Must be greater than 0.
Maximum time to wait in milliseconds. Defaults to `300000` (5 minutes). Must be greater than 0. Throws `TimeoutError` if exceeded.
Callback invoked on each poll with the current agent status. Use this to update a progress UI.
### Returns
`Promise` -- resolves when the agent reaches `DEACTIVATED` status.
### Errors
* **`TimeoutError`**: Thrown if the timeout is exceeded before the agent is deactivated. The agent may still be deactivating; call `status()` to check.
* **`ValidationError`**: Thrown if `interval` or `timeout` is not a positive number.
### Examples
```typescript theme={null}
import { TimeoutError } from '@gizatech/agent-sdk';
try {
const finalStatus = await agent.waitForDeactivation({
interval: 3000,
timeout: 600000, // 10 minutes
onUpdate: (status) => {
console.log(`Current status: ${status}`);
},
});
console.log('Agent deactivated at:', finalStatus.last_deactivation_date);
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Still deactivating, check again later');
const current = await agent.status();
console.log('Current status:', current.status);
}
}
```
***
## fees()
Get the fee information for the agent's smart account.
### Signature
```typescript theme={null}
fees(): Promise
```
### Returns
`Promise`
### FeeResponse Type
```typescript theme={null}
interface FeeResponse {
percentage_fee: number;
fee: number;
}
```
### Examples
```typescript theme={null}
const feeInfo = await agent.fees();
console.log(`Fee percentage: ${feeInfo.percentage_fee}%`);
console.log(`Fee amount: ${feeInfo.fee}`);
```
***
## limit()
Get the withdrawal limit for a given origin wallet (EOA).
### Signature
```typescript theme={null}
limit(eoa: Address): Promise
```
### Parameters
The origin wallet address (`0x`-prefixed hex string) to check the limit for.
### Returns
`Promise`
### LimitResponse Type
```typescript theme={null}
interface LimitResponse {
limit: number;
}
```
### Examples
```typescript theme={null}
const originWallet = '0xYourOriginWalletAddress' as const;
const limitInfo = await agent.limit(originWallet);
console.log(`Withdrawal limit: ${limitInfo.limit}`);
```
***
## Complete Withdrawal Flow
This example shows a complete withdrawal flow: checking fees, performing a full withdrawal, and waiting for completion.
```typescript theme={null}
import { Giza, Chain, TimeoutError } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
// 1. Check fees before withdrawing
const feeInfo = await agent.fees();
console.log(`Withdrawal fee: ${feeInfo.percentage_fee}%`);
// 2. Check current status
const currentStatus = await agent.status();
console.log(`Agent is: ${currentStatus.status}`);
// 3. Initiate full withdrawal
const result = await agent.withdraw();
console.log('Withdrawal initiated');
// 4. Wait for deactivation
try {
const finalStatus = await agent.waitForDeactivation({
interval: 5000,
timeout: 300000,
onUpdate: (status) => {
console.log(` -> ${status}`);
},
});
console.log('Withdrawal complete:', finalStatus.status);
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Withdrawal still processing...');
} else {
throw error;
}
}
```
After a full withdrawal, the agent is deactivated. To use the agent again, you must re-activate it with `agent.activate()`.
# Giza Client
Source: https://docs.gizatech.xyz/sdk-reference/giza
Main SDK entry point for configuration, agent creation, and chain-level queries
## Overview
The `Giza` class is the primary entry point of the SDK. It manages authentication, HTTP transport, and chain-scoped configuration. Use it to create `Agent` handles, query protocol data, run the optimizer, and check system health.
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({
chain: Chain.BASE,
// apiKey, partner, apiUrl fall back to env vars
});
```
## Constructor
```typescript theme={null}
new Giza(config: GizaConfig)
```
Creates a new SDK client. See the [GizaConfig reference](/sdk-reference/overview#configuration) for all available options.
Configuration object specifying the target chain and credentials.
The constructor validates all inputs and resolves environment variable fallbacks. It throws a `ValidationError` if any required credential is missing or if the chain ID is invalid.
## Environment Variable Fallback
When a credential is omitted from the constructor config, the SDK reads the corresponding environment variable:
| Config Field | Environment Variable | Required |
| ------------ | -------------------- | ----------------------- |
| `apiKey` | `GIZA_API_KEY` | Yes (via config or env) |
| `partner` | `GIZA_PARTNER_NAME` | Yes (via config or env) |
| `apiUrl` | `GIZA_API_URL` | Yes (via config or env) |
If neither the config field nor the environment variable is set, the constructor throws a `ValidationError` with a message indicating which value is missing.
## Agent Factory Methods
These methods create or retrieve `Agent` handles bound to a specific smart-account wallet address.
### `agent(wallet)`
```typescript theme={null}
agent(wallet: Address): Agent
```
Returns an `Agent` handle for a known smart-account address without making any API call. Use this when you already have the smart-account address stored (for example, from a previous `createAgent` call).
The smart-account wallet address (`0x`-prefixed hex string).
**Returns:** `Agent`
```typescript theme={null}
const agent = giza.agent('0x1234567890abcdef1234567890abcdef12345678');
const info = await agent.portfolio();
```
***
### `createAgent(eoa)`
```typescript theme={null}
async createAgent(eoa: Address): Promise
```
Creates a new smart account for the given externally-owned account (EOA) and returns an `Agent` bound to the new smart-account address.
The user's externally-owned account address.
**Returns:** `Promise` -- the Agent is bound to the newly created smart-account address.
```typescript theme={null}
const agent = await giza.createAgent('0xUserEOA...');
console.log('Smart account:', agent.wallet);
```
***
### `getAgent(eoa)`
```typescript theme={null}
async getAgent(eoa: Address): Promise
```
Looks up an existing smart account by EOA and returns an `Agent` bound to it. Use this when the smart account was created previously and you need to recover the handle.
The user's externally-owned account address.
**Returns:** `Promise`
```typescript theme={null}
const agent = await giza.getAgent('0xUserEOA...');
const portfolio = await agent.portfolio();
```
***
### `getSmartAccount(eoa)`
```typescript theme={null}
async getSmartAccount(eoa: Address): Promise
```
Returns full smart-account metadata (address, backend wallet, origin wallet, chain) without creating an `Agent` handle. Useful when you need the raw account data.
The user's externally-owned account address.
**Returns:** `Promise`
```typescript theme={null}
interface SmartAccountInfo {
smartAccountAddress: Address;
backendWallet: Address;
origin_wallet: Address;
chain: Chain;
}
```
```typescript theme={null}
const account = await giza.getSmartAccount('0xUserEOA...');
console.log('Smart account:', account.smartAccountAddress);
console.log('Backend wallet:', account.backendWallet);
```
## Chain-Level Queries
These methods query data scoped to the chain configured on the `Giza` client.
### `protocols(token)`
```typescript theme={null}
async protocols(token: Address): Promise
```
Returns the list of active protocol names available for a given token on the current chain.
The token contract address.
**Returns:** `Promise` -- `{ protocols: string[] }`
```typescript theme={null}
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const { protocols } = await giza.protocols(USDC);
console.log('Available protocols:', protocols);
// ['aave', 'compound', 'moonwell', ...]
```
***
### `protocolSupply(token)`
```typescript theme={null}
async protocolSupply(token: Address): Promise
```
Returns supply data for each protocol supporting the given token.
The token contract address.
**Returns:** `Promise`
```typescript theme={null}
const supply = await giza.protocolSupply(
'0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
);
for (const p of supply.protocols) {
console.log(`${p.protocol}: ${p.supply}`);
}
```
***
### `tokens()`
```typescript theme={null}
async tokens(): Promise
```
Returns all supported tokens on the current chain with their metadata (address, symbol, decimals, balance, price).
**Returns:** `Promise` -- `{ tokens: TokenInfo[] }`
```typescript theme={null}
const { tokens } = await giza.tokens();
for (const token of tokens) {
console.log(`${token.symbol}: ${token.address}`);
}
```
***
### `stats()`
```typescript theme={null}
async stats(): Promise
```
Returns aggregate statistics for the current chain: total balance, deposits, users, transactions, APR, and liquidity distribution.
**Returns:** `Promise`
```typescript theme={null}
const stats = await giza.stats();
console.log(`Total users: ${stats.total_users}`);
console.log(`Total APR: ${stats.total_apr}%`);
```
***
### `tvl()`
```typescript theme={null}
async tvl(): Promise
```
Returns the total value locked on the current chain.
**Returns:** `Promise` -- `{ tvl: number }`
```typescript theme={null}
const { tvl } = await giza.tvl();
console.log(`TVL: $${tvl}`);
```
## Optimizer
The optimizer provides capital allocation recommendations. See the [Optimizer reference](/sdk-reference/optimizer) for full documentation.
### `optimize(options)`
```typescript theme={null}
async optimize(options: OptimizeOptions): Promise
```
Computes optimal capital allocation across protocols for a given token and capital amount. Returns the allocation plan, action steps, and execution-ready calldata.
```typescript theme={null}
const result = await giza.optimize({
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
capital: '1000000000', // in token smallest unit
protocols: ['aave', 'compound'],
currentAllocations: { aave: '500000000', compound: '500000000' },
});
console.log('Optimal allocations:', result.optimization_result.allocations);
```
## System
### `health()`
```typescript theme={null}
async health(): Promise
```
Returns the API health status, version, and server time.
```typescript theme={null}
const health = await giza.health();
console.log(`API version: ${health.version}, status: ${health.message}`);
```
***
### `getApiConfig()`
```typescript theme={null}
async getApiConfig(): Promise
```
Returns the global API configuration, including minimum withdrawal thresholds, optimizer settings, and per-chain configuration.
```typescript theme={null}
const config = await giza.getApiConfig();
console.log(`Min withdraw: $${config.min_withdraw_usd}`);
```
***
### `chains()`
```typescript theme={null}
async chains(): Promise
```
Returns the list of supported chain IDs.
```typescript theme={null}
const { chain_ids } = await giza.chains();
console.log('Supported chains:', chain_ids);
```
## Accessors
### `getChain()`
```typescript theme={null}
getChain(): Chain
```
Returns the `Chain` enum value configured on this client.
***
### `getApiUrl()`
```typescript theme={null}
getApiUrl(): string
```
Returns the resolved API base URL.
## Next Steps
Wallet-scoped lifecycle, monitoring, and operations
Capital allocation optimization
SDK architecture and configuration reference
End-to-end integration tutorial
# Optimizer
Source: https://docs.gizatech.xyz/sdk-reference/optimizer
Stateless capital allocation optimization
## Overview
The optimizer provides stateless capital allocation optimization across DeFi protocols. It computes optimal allocations, generates action plans, and returns execution-ready calldata.
Optimizer methods are on the `Giza` client, not on the `Agent` instance. They operate at the chain level and do not require a specific smart account.
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
// Optimizer methods are called on the Giza client
const result = await giza.optimize({ ... });
```
***
## optimize()
Compute the optimal allocation of capital across a set of protocols, given the current allocations and constraints. Returns the target allocations, an action plan describing the required moves, and execution-ready calldata.
### Signature
```typescript theme={null}
giza.optimize(options: OptimizeOptions): Promise
```
### Parameters
Optimization input parameters.
Token address to optimize for (e.g., USDC).
Total capital in the token's smallest unit (e.g., `'1000000000'` for 1000 USDC). Must be a positive integer string.
Current allocation per protocol, as a map of protocol name to amount in smallest units. Use `'0'` for protocols with no current allocation.
List of protocol names to consider for allocation. Must contain at least one entry.
Target chain. Defaults to the chain configured on the `Giza` client.
Allocation constraints to apply. See [Constraints](#constraints) below.
Smart account address. When provided, the optimizer can use wallet-specific data for more accurate results.
### Returns
`Promise`
### Response Types
```typescript theme={null}
interface OptimizeResponse {
optimization_result: OptimizationResult;
action_plan: ActionDetail[];
calldata: CalldataInfo[];
}
interface OptimizationResult {
allocations: ProtocolAllocation[];
total_costs: number;
weighted_apr_initial: number;
weighted_apr_final: number;
apr_improvement: number;
gas_estimate_usd?: number;
break_even_days?: number;
}
interface ProtocolAllocation {
protocol: string;
allocation: string;
apr: number;
}
interface ActionDetail {
action_type: 'deposit' | 'withdraw';
protocol: string;
amount: string;
underlying_amount?: string;
}
interface CalldataInfo {
contract_address: string;
function_name: string;
parameters: string[];
value: string;
protocol: string;
description: string;
}
```
### Examples
```typescript Basic optimization theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const result = await giza.optimize({
token: USDC,
capital: '1000000000', // 1000 USDC
currentAllocations: {
aave: '500000000',
morpho: '500000000',
},
protocols: ['aave', 'morpho', 'moonwell'],
});
// Optimal allocations
console.log('Target allocations:');
for (const alloc of result.optimization_result.allocations) {
console.log(` ${alloc.protocol}: ${alloc.allocation} (${alloc.apr}% APR)`);
}
// APR improvement
const { optimization_result } = result;
console.log(`APR: ${optimization_result.weighted_apr_initial}% -> ${optimization_result.weighted_apr_final}%`);
console.log(`Improvement: +${optimization_result.apr_improvement}%`);
if (optimization_result.gas_estimate_usd) {
console.log(`Gas estimate: $${optimization_result.gas_estimate_usd}`);
}
if (optimization_result.break_even_days) {
console.log(`Break-even: ${optimization_result.break_even_days} days`);
}
```
```typescript With constraints theme={null}
import { Giza, Chain, WalletConstraints } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const USDC = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
const result = await giza.optimize({
token: USDC,
capital: '5000000000', // 5000 USDC
currentAllocations: {
aave: '0',
morpho: '0',
moonwell: '0',
},
protocols: ['aave', 'morpho', 'moonwell'],
constraints: [
{
kind: WalletConstraints.MAX_ALLOCATION_AMOUNT_PER_PROTOCOL,
params: { max_allocation: 50 },
},
{
kind: WalletConstraints.MIN_PROTOCOLS,
params: { min_protocols: 2 },
},
],
});
console.log('Constrained allocations:');
for (const alloc of result.optimization_result.allocations) {
console.log(` ${alloc.protocol}: ${alloc.allocation}`);
}
```
```typescript Reading the action plan theme={null}
const result = await giza.optimize({
token: USDC,
capital: '2000000000',
currentAllocations: { aave: '1000000000', morpho: '1000000000' },
protocols: ['aave', 'morpho', 'moonwell'],
});
// Action plan: what needs to happen
console.log('Action plan:');
for (const action of result.action_plan) {
console.log(` ${action.action_type} ${action.amount} on ${action.protocol}`);
}
// Calldata: ready to execute on-chain
console.log('Calldata:');
for (const call of result.calldata) {
console.log(` ${call.protocol}: ${call.function_name}`);
console.log(` Contract: ${call.contract_address}`);
console.log(` Description: ${call.description}`);
}
```
***
## Constraints
Constraints control how the optimizer distributes capital. Pass them in the `constraints` array of `OptimizeOptions`.
### WalletConstraints Enum
```typescript theme={null}
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',
}
```
### ConstraintConfig (Optimizer)
```typescript theme={null}
interface ConstraintConfig {
kind: WalletConstraints;
params: Record;
}
```
The optimizer uses its own `ConstraintConfig` type where `kind` is a `WalletConstraints` enum value. The agent's `ConstraintConfig` uses a plain `string` for `kind`. Both are exported from the SDK -- use `OptimizerConstraintConfig` for the optimizer variant if you need to distinguish them.
### Constraint Reference
| Constraint | Description | Example Params |
| ------------------------------------ | ---------------------------------------------- | ------------------------------ |
| `MIN_PROTOCOLS` | Require allocation across at least N protocols | `{ min_protocols: 2 }` |
| `MAX_ALLOCATION_AMOUNT_PER_PROTOCOL` | Cap each protocol at N% of total capital | `{ max_allocation: 50 }` |
| `MAX_AMOUNT_PER_PROTOCOL` | Cap each protocol at an absolute amount | `{ max_amount: 500000000 }` |
| `MIN_AMOUNT` | Minimum total allocation amount | `{ min_amount: 100000000 }` |
| `EXCLUDE_PROTOCOL` | Exclude a specific protocol | `{ protocol: 'compound' }` |
| `MIN_ALLOCATION_AMOUNT_PER_PROTOCOL` | Minimum allocation per protocol | `{ min_allocation: 50000000 }` |
### Constraint Example
```typescript theme={null}
import { WalletConstraints } from '@gizatech/agent-sdk';
const constraints = [
{
kind: WalletConstraints.MAX_ALLOCATION_AMOUNT_PER_PROTOCOL,
params: { max_allocation: 40 },
},
{
kind: WalletConstraints.MIN_PROTOCOLS,
params: { min_protocols: 3 },
},
{
kind: WalletConstraints.EXCLUDE_PROTOCOL,
params: { protocol: 'compound' },
},
];
const result = await giza.optimize({
token: USDC,
capital: '10000000000',
currentAllocations: { aave: '0', morpho: '0', moonwell: '0' },
protocols: ['aave', 'morpho', 'moonwell'],
constraints,
});
```
# Overview
Source: https://docs.gizatech.xyz/sdk-reference/overview
TypeScript SDK for building on Giza autonomous yield agents
## Introduction
The `@gizatech/agent-sdk` is a TypeScript SDK for managing Giza DeFi yield optimization agents. It provides a resource-oriented, type-safe interface and handles authentication, request retries, pagination, and error handling.
The SDK wraps the [HTTP API](/api-reference/introduction) in a convenient TypeScript interface with automatic authentication, type safety, and structured error handling.
## Installation
```bash npm theme={null}
npm install @gizatech/agent-sdk
```
```bash bun theme={null}
bun add @gizatech/agent-sdk
```
```bash yarn theme={null}
yarn add @gizatech/agent-sdk
```
## Quick Start
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
// Credentials fall back to GIZA_API_KEY, GIZA_PARTNER_NAME, GIZA_API_URL env vars
const giza = new Giza({ chain: Chain.BASE });
// Create a smart-account agent for a user's EOA
const agent = await giza.createAgent('0xYourEOA...');
// Activate the agent after the user deposits USDC
await agent.activate({
owner: '0xYourEOA...',
token: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
protocols: ['aave', 'compound'],
txHash: '0xDepositTxHash...',
});
// Check the current APR
const { apr } = await agent.apr();
console.log(`Current APR: ${apr}%`);
```
## SDK Architecture
The SDK follows a resource-oriented design with two primary classes:
* **`Giza`** -- the top-level client. Handles configuration, authentication, and chain-level queries (protocols, tokens, stats, optimizer). It also acts as a factory for `Agent` instances.
* **`Agent`** -- a wallet-scoped handle bound to a single smart-account address. All agent lifecycle, monitoring, withdrawal, rewards, and protocol operations live here. You never pass a wallet address to individual methods because the `Agent` already knows it.
The typical flow is:
1. Create a `Giza` client with your chain and credentials.
2. Obtain an `Agent` via `giza.createAgent(eoa)`, `giza.getAgent(eoa)`, or `giza.agent(wallet)`.
3. Call methods on the `Agent` instance for all wallet-scoped operations.
```typescript theme={null}
const giza = new Giza({ chain: Chain.BASE });
// Three ways to get an Agent handle:
const agent1 = await giza.createAgent('0xEOA...'); // new smart account
const agent2 = await giza.getAgent('0xEOA...'); // existing smart account
const agent3 = giza.agent('0xSmartAccount...'); // known address, no API call
```
## Configuration
All configuration is passed through the `GizaConfig` interface. Credentials fall back to environment variables when omitted.
| Parameter | Type | Required | Default | Env Fallback | Description |
| ------------- | --------- | -------- | ------- | ------------------- | ------------------------------------ |
| `chain` | `Chain` | Yes | -- | -- | Target blockchain network |
| `apiKey` | `string` | No | -- | `GIZA_API_KEY` | Partner API key |
| `partner` | `string` | No | -- | `GIZA_PARTNER_NAME` | Partner identifier |
| `apiUrl` | `string` | No | -- | `GIZA_API_URL` | Giza backend URL |
| `timeout` | `number` | No | `45000` | -- | HTTP request timeout in ms |
| `enableRetry` | `boolean` | No | `false` | -- | Auto-retry on 5xx and network errors |
```typescript theme={null}
const giza = new Giza({
chain: Chain.BASE,
apiKey: 'your-api-key', // or set GIZA_API_KEY
partner: 'your-partner', // or set GIZA_PARTNER_NAME
apiUrl: 'https://api.gizatech.xyz', // or set GIZA_API_URL
timeout: 60000,
enableRetry: true,
});
```
## Supported Chains
```typescript theme={null}
import { Chain } from '@gizatech/agent-sdk';
Chain.ETHEREUM // 1 - Ethereum Mainnet
Chain.POLYGON // 137 - Polygon Mainnet
Chain.BASE // 8453 - Base Mainnet
Chain.ARBITRUM // 42161 - Arbitrum One
Chain.SEPOLIA // 11155111 - Sepolia Testnet
Chain.BASE_SEPOLIA // 84532 - Base Sepolia Testnet
Chain.DEVNET // -1 - Development Network
```
## Error Handling
The SDK provides a typed error hierarchy so you can handle failures precisely:
| Error Class | When It Occurs |
| ----------------- | ---------------------------------------------------------------- |
| `ValidationError` | Invalid input parameters (bad address format, missing fields) |
| `GizaAPIError` | API returned an HTTP error (includes `statusCode` and `message`) |
| `TimeoutError` | Request exceeded the configured timeout |
| `NetworkError` | Network connectivity failure (DNS, connection refused) |
All errors extend the base `GizaError` class.
```typescript theme={null}
import {
ValidationError,
GizaAPIError,
TimeoutError,
NetworkError,
} from '@gizatech/agent-sdk';
try {
await agent.activate({ /* ... */ });
} 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('Timed out:', error.message);
} else if (error instanceof NetworkError) {
console.error('Network failure:', error.message);
}
}
```
## SDK vs HTTP API
| Feature | SDK | HTTP API |
| -------------- | -------------------------- | ----------------------- |
| Type Safety | Full TypeScript types | Manual typing |
| Authentication | Automatic via config/env | Manual headers |
| Error Handling | Typed error classes | Manual response parsing |
| Retries | Built-in (opt-in) | Manual implementation |
| Pagination | Async-iterable `Paginator` | Manual page tracking |
| Language | TypeScript / JavaScript | Any HTTP client |
For direct HTTP access or non-JavaScript integrations, see the API Reference.
## Next Steps
Client configuration, agent factory methods, and chain-level queries
Wallet-scoped lifecycle, monitoring, withdrawals, and rewards
Capital allocation optimization
End-to-end integration tutorial
# Paginator
Source: https://docs.gizatech.xyz/sdk-reference/paginator
Async-iterable pagination utility for collection methods
## Overview
`Paginator` is an async-iterable class returned by all collection methods on the `Agent` class (transactions, executions, logs, rewards). It provides three ways to consume paginated API results:
1. **Async iteration** with `for await...of` -- automatically pages through all results.
2. **`.first(count)`** -- fetch the first N items as an array.
3. **`.page(num, opts)`** -- fetch a specific page with metadata.
You never construct a `Paginator` directly. It is returned by agent methods like `agent.transactions()`, `agent.executions()`, `agent.rewards()`, and others.
```typescript theme={null}
import { Giza, Chain } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
// Each of these returns a Paginator instance
const txPaginator = agent.transactions();
const execPaginator = agent.executions();
const logPaginator = agent.logs();
const rewardPaginator = agent.rewards();
```
***
## Usage Patterns
### Pattern 1: Async Iteration
The paginator implements `AsyncIterable`, so you can use `for await...of` to iterate over all items across all pages. The paginator automatically fetches subsequent pages as needed.
```typescript theme={null}
for await (const tx of agent.transactions()) {
console.log(tx.action, tx.amount);
}
```
Async iteration fetches all pages sequentially. For large datasets, consider using `.first()` or `.page()` to limit the amount of data retrieved.
### Pattern 2: First N Items
Use `.first(count)` to get an array of the first N items. This fetches only the pages needed to fulfill the request.
```typescript theme={null}
import { SortOrder } from '@gizatech/agent-sdk';
const recent = await agent.transactions({
sort: SortOrder.DATE_DESC,
}).first(5);
for (const tx of recent) {
console.log(`${tx.date}: ${tx.action} ${tx.amount} ${tx.token_type}`);
}
```
When called without an argument, `.first()` returns the first page of items using the configured page size.
```typescript theme={null}
// Returns up to 20 items (default page size)
const firstPage = await agent.transactions().first();
```
### Pattern 3: Specific Page
Use `.page(num, opts)` to fetch a specific page and get pagination metadata alongside the items.
```typescript theme={null}
const page2 = await agent.transactions().page(2, { limit: 25 });
console.log(`Page ${page2.page} of ${Math.ceil(page2.total / page2.limit)}`);
console.log(`Total items: ${page2.total}`);
console.log(`Has more: ${page2.hasMore}`);
for (const tx of page2.items) {
console.log(tx.transaction_hash);
}
```
***
## Class Reference
### Paginator\
```typescript theme={null}
class Paginator implements AsyncIterable {
async *[Symbol.asyncIterator](): AsyncIterableIterator;
async page(num: number, opts?: { limit?: number }): Promise>;
async first(count?: number): Promise;
}
```
### [Symbol.asyncIterator]()
Enables `for await...of` iteration. Automatically fetches pages until all items have been yielded.
**Returns**: `AsyncIterableIterator`
### page()
Fetch a specific page of results with pagination metadata.
The 1-based page number to fetch.
Optional override for the page size.
Number of items per page. Defaults to the limit configured when the paginator was created (typically `20`).
**Returns**: `Promise>`
### first()
Fetch the first N items as an array.
Number of items to return. When omitted, returns the first page using the configured page size.
**Returns**: `Promise`
***
## PaginatedResponse\
The response object returned by `.page()`.
```typescript theme={null}
interface PaginatedResponse {
items: T[];
total: number;
page: number;
limit: number;
hasMore: boolean;
}
```
| Field | Type | Description |
| --------- | --------- | ------------------------------------------- |
| `items` | `T[]` | The items on this page |
| `total` | `number` | Total number of items across all pages |
| `page` | `number` | Current page number (1-based) |
| `limit` | `number` | Items per page |
| `hasMore` | `boolean` | Whether there are more pages after this one |
***
## PageFetcher\
The internal type for the function that fetches a page of results. This is used internally by the SDK and is not needed for normal usage.
```typescript theme={null}
type PageFetcher = (
page: number,
limit: number,
) => Promise>;
```
***
## Methods That Return Paginators
The following `Agent` methods return `Paginator` instances:
| Method | Item Type | Reference |
| ------------------------- | ------------------------------ | ------------------------------------------------- |
| `agent.transactions()` | `Transaction` | [Transactions](/sdk-reference/agent/transactions) |
| `agent.executions()` | `ExecutionWithTransactionsDTO` | [Transactions](/sdk-reference/agent/transactions) |
| `agent.executionLogs(id)` | `LogDTO` | [Transactions](/sdk-reference/agent/transactions) |
| `agent.logs()` | `LogDTO` | [Transactions](/sdk-reference/agent/transactions) |
| `agent.rewards()` | `RewardDTO` | [Rewards](/sdk-reference/agent/rewards) |
| `agent.rewardHistory()` | `RewardDTO` | [Rewards](/sdk-reference/agent/rewards) |
All accept an optional `PaginationOptions` parameter:
```typescript theme={null}
interface PaginationOptions {
limit?: number;
sort?: string;
}
```
***
## Building a Paginated UI
This example shows how to use `.page()` to build a paginated list with navigation.
```typescript theme={null}
import { Giza, Chain, SortOrder } from '@gizatech/agent-sdk';
const giza = new Giza({ chain: Chain.BASE });
const agent = giza.agent('0xYourSmartAccountAddress');
const PAGE_SIZE = 10;
let currentPage = 1;
async function loadPage(pageNum: number) {
const result = await agent.transactions({
sort: SortOrder.DATE_DESC,
}).page(pageNum, { limit: PAGE_SIZE });
const totalPages = Math.ceil(result.total / result.limit);
return {
items: result.items,
page: result.page,
totalPages,
total: result.total,
hasNext: result.hasMore,
hasPrev: result.page > 1,
};
}
// Load first page
const page1 = await loadPage(1);
console.log(`Showing page ${page1.page} of ${page1.totalPages}`);
console.log(`${page1.total} total transactions`);
// Load next page
if (page1.hasNext) {
const page2 = await loadPage(2);
console.log(`Showing page ${page2.page} of ${page2.totalPages}`);
}
```
# Types Reference
Source: https://docs.gizatech.xyz/sdk-reference/types
Complete reference of all exported types, interfaces, enums, and constants
## Overview
This page lists every type exported from `@gizatech/agent-sdk`. Types are grouped by category. All types can be imported directly:
```typescript theme={null}
import {
Giza, Agent, Chain, Paginator,
type Address, type Transaction, type OptimizeOptions,
} from '@gizatech/agent-sdk';
```
***
## Configuration
### GizaConfig
Options passed to the `Giza` constructor. Credentials fall back to environment variables when omitted.
```typescript theme={null}
interface GizaConfig {
chain: Chain;
apiKey?: string;
partner?: string;
apiUrl?: string;
timeout?: number;
enableRetry?: boolean;
}
```
### ResolvedGizaConfig
Internal configuration after defaults and environment variables are resolved.
```typescript theme={null}
interface ResolvedGizaConfig {
chain: Chain;
apiKey: string;
partner: string;
apiUrl: string;
agentId: string;
timeout: number;
enableRetry: boolean;
}
```
***
## Common
### Address
Ethereum address type. A `0x`-prefixed hex string.
```typescript theme={null}
type Address = `0x${string}`;
```
### Chain
Supported blockchain networks.
```typescript theme={null}
enum Chain {
DEVNET = -1,
ETHEREUM = 1,
POLYGON = 137,
CHAIN_999 = 999,
BASE = 8453,
CHAIN_9745 = 9745,
SEPOLIA = 11155111,
ARBITRUM = 42161,
BASE_SEPOLIA = 84532,
}
```
### GizaError
Base error class for all SDK errors.
```typescript theme={null}
class GizaError extends Error {
constructor(message: string);
}
```
### ValidationError
Thrown when input validation fails (invalid address, missing required fields, etc.).
```typescript theme={null}
class ValidationError extends GizaError {
constructor(message: string);
}
```
### NotImplementedError
Thrown when a feature is not yet implemented.
```typescript theme={null}
class NotImplementedError extends GizaError {
constructor(message: string);
}
```
***
## Agent Options
### ActivateOptions
```typescript theme={null}
interface ActivateOptions {
owner: Address;
token: Address;
protocols: string[];
txHash: string;
constraints?: ConstraintConfig[];
}
```
### AprOptions
```typescript theme={null}
interface AprOptions {
startDate?: string;
endDate?: string;
useExactEndDate?: boolean;
}
```
### DeactivateOptions
```typescript theme={null}
interface DeactivateOptions {
transfer?: boolean;
}
```
### PaginationOptions
```typescript theme={null}
interface PaginationOptions {
limit?: number;
sort?: string;
}
```
### PerformanceOptions
```typescript theme={null}
interface PerformanceOptions {
from?: string;
}
```
### WaitForDeactivationOptions
```typescript theme={null}
interface WaitForDeactivationOptions {
interval?: number;
timeout?: number;
onUpdate?: (status: AgentStatus) => void;
}
```
***
## Agent Responses
### SmartAccountInfo
```typescript theme={null}
interface SmartAccountInfo {
smartAccountAddress: Address;
backendWallet: Address;
origin_wallet: Address;
chain: Chain;
}
```
### ActivateResponse
```typescript theme={null}
interface ActivateResponse {
message: string;
wallet: string;
}
```
### DeactivateResponse
```typescript theme={null}
interface DeactivateResponse {
message: string;
}
```
### TopUpResponse
```typescript theme={null}
interface TopUpResponse {
message: string;
}
```
### RunResponse
```typescript theme={null}
interface RunResponse {
status: string;
}
```
### AgentInfo
```typescript theme={null}
interface AgentInfo {
wallet: Address;
deposits: Deposit[];
withdraws?: Withdraw[];
status: AgentStatus;
activation_date: string;
last_deactivation_date?: string;
last_reactivation_date?: string;
selected_protocols: string[];
current_protocols?: string[];
current_token?: string;
eoa?: Address;
}
```
### PerformanceChartResponse
```typescript theme={null}
interface PerformanceChartResponse {
performance: PerformanceData[];
}
```
### PerformanceData
```typescript theme={null}
interface PerformanceData {
date: string;
value: number;
value_in_usd?: number;
accrued_rewards?: AccruedRewardsBySymbol;
portfolio?: Portfolio;
agent_token_amount?: number;
}
```
### WalletAprResponse
```typescript theme={null}
interface WalletAprResponse {
apr: number;
sub_periods?: WalletAprSubPeriod[];
}
```
### WalletAprSubPeriod
```typescript theme={null}
interface WalletAprSubPeriod {
start_date: string;
end_date: string;
return_: number;
initial_value: number;
}
```
### AprByTokenResponse
```typescript theme={null}
type AprByTokenResponse = AllocatedValue[];
```
### AllocatedValue
```typescript theme={null}
interface AllocatedValue {
value: number;
value_in_usd: number;
base_apr?: number;
total_apr?: number;
}
```
### Portfolio
```typescript theme={null}
type Portfolio = Record;
```
### AccruedRewardsWithValue
```typescript theme={null}
interface AccruedRewardsWithValue {
locked: number;
unlocked: number;
locked_value: number;
locked_value_usd: number;
unlocked_value: number;
unlocked_value_usd: number;
claimed?: number;
claimed_value?: number;
claimed_value_usd?: number;
}
```
### AccruedRewardsBySymbol
```typescript theme={null}
type AccruedRewardsBySymbol = Record;
```
### Transaction
```typescript theme={null}
interface Transaction {
action: TxAction;
date: string;
amount: number;
amount_out?: number;
token_type: string;
status: TxStatus;
transaction_hash?: string;
protocol?: string;
new_token?: string;
correlation_id?: string;
apr?: number;
block_number?: number;
}
```
### TransactionHistoryResponse
```typescript theme={null}
interface TransactionHistoryResponse {
transactions: Transaction[];
pagination: PaginationInfo;
}
```
### PaginationInfo
```typescript theme={null}
interface PaginationInfo {
page: number;
items_per_page: number;
total_pages: number;
total_items: number;
}
```
### WithdrawResponse
```typescript theme={null}
type WithdrawResponse =
| FullWithdrawResponse
| PartialWithdrawResponse;
```
### FullWithdrawResponse
```typescript theme={null}
interface FullWithdrawResponse {
message: string;
}
```
### PartialWithdrawResponse
```typescript theme={null}
interface PartialWithdrawResponse {
date: string;
amount: number;
value: number;
withdraw_details: WithdrawDetail[];
}
```
### WithdrawDetail
```typescript theme={null}
interface WithdrawDetail {
token: string;
amount: string;
value: number;
value_in_usd: number;
principal_amount?: number;
yield_amount?: number;
fee_amount?: number;
tx_hash?: string;
block_number?: number;
}
```
### WithdrawalStatusResponse
```typescript theme={null}
interface WithdrawalStatusResponse {
status: AgentStatus;
wallet: Address;
activation_date: string;
last_deactivation_date?: string;
last_reactivation_date?: string;
}
```
### FeeResponse
```typescript theme={null}
interface FeeResponse {
percentage_fee: number;
fee: number;
}
```
### LimitResponse
```typescript theme={null}
interface LimitResponse {
limit: number;
}
```
### ClaimedReward
```typescript theme={null}
interface ClaimedReward {
token: string;
amount: number;
amount_float: number;
current_price_in_underlying: number;
}
```
### ClaimedRewardsResponse
```typescript theme={null}
interface ClaimedRewardsResponse {
rewards: ClaimedReward[];
}
```
### DepositListResponse
```typescript theme={null}
interface DepositListResponse {
deposits: Deposit[];
}
```
### Deposit
```typescript theme={null}
interface Deposit {
amount: number;
token_type: string;
date?: string;
tx_hash?: string;
block_number?: number;
}
```
### Withdraw
```typescript theme={null}
interface Withdraw {
date: string;
amount: number;
value: number;
withdraw_details: WithdrawDetail[];
}
```
### ExecutionWithTransactionsDTO
```typescript theme={null}
interface ExecutionWithTransactionsDTO {
id: string;
execution_plan: unknown;
execution_type: string;
status: ExecutionStatus;
created_at: string;
transactions: Transaction[];
}
```
### PaginatedExecutionDTO
```typescript theme={null}
interface PaginatedExecutionDTO {
items: ExecutionWithTransactionsDTO[];
total: number;
}
```
### LogDTO
```typescript theme={null}
interface LogDTO {
type: string;
data: unknown;
}
```
### PaginatedLogDTO
```typescript theme={null}
interface PaginatedLogDTO {
items: LogDTO[];
total: number;
}
```
### RewardDTO
```typescript theme={null}
interface RewardDTO {
user_id: string;
base_apr: number;
extra_apr: number;
ticker: string;
reward_amount: number;
group: string;
transaction_hash: string;
start_date: string;
end_date: string;
id: string;
created_at: string;
updated_at: string;
}
```
### PaginatedRewardDTO
```typescript theme={null}
interface PaginatedRewardDTO {
items: RewardDTO[];
total: number;
}
```
### Protocol
```typescript theme={null}
interface Protocol {
name: string;
is_active: boolean;
description: string;
tvl: number;
apr: number | null;
pools: ProtocolPool[] | null;
created_at: string;
updated_at: string | null;
chain_id: number;
parent_protocol: string;
link: string;
address: string | null;
agent_token: string | null;
title: string | null;
}
```
### ProtocolPool
```typescript theme={null}
interface ProtocolPool {
name: string;
apy: number;
}
```
### ProtocolsResponse
```typescript theme={null}
interface ProtocolsResponse {
protocols: string[];
}
```
### ProtocolsRawResponse
```typescript theme={null}
interface ProtocolsRawResponse {
protocols: Protocol[];
}
```
### ProtocolSupply
```typescript theme={null}
interface ProtocolSupply {
protocol: string;
supply: number;
tokens: string[];
}
```
### ProtocolsSupplyResponse
```typescript theme={null}
interface ProtocolsSupplyResponse {
protocols: ProtocolSupply[];
}
```
### ConstraintConfig (Agent)
```typescript theme={null}
interface ConstraintConfig {
kind: string;
params: Record;
}
```
### ConstraintConfigResponse
```typescript theme={null}
interface ConstraintConfigResponse {
[key: string]: unknown;
}
```
### ChainConfigResponse
```typescript theme={null}
interface ChainConfigResponse {
[key: string]: unknown;
}
```
### GlobalConfigResponse
```typescript theme={null}
interface GlobalConfigResponse {
min_withdraw_usd: number;
optimizer_threshold_usd: number;
max_protocol_liquidity_percentage: number;
constraints: ConstraintConfigResponse;
chains: Record;
}
```
### HealthcheckResponse
```typescript theme={null}
interface HealthcheckResponse {
message: string;
version: string;
time: string;
}
```
### ChainsResponse
```typescript theme={null}
interface ChainsResponse {
chain_ids: number[];
}
```
### TokenDistributionItem
```typescript theme={null}
interface TokenDistributionItem {
token: string;
amount: number;
percentage: number;
}
```
### ProtocolDistribution
```typescript theme={null}
interface ProtocolDistribution {
protocol: string;
amount: number;
percentage: number;
}
```
### LiquidityDistribution
```typescript theme={null}
interface LiquidityDistribution {
initial_deposits: TokenDistributionItem[];
current_tokens: TokenDistributionItem[];
protocols: ProtocolDistribution[];
}
```
### Statistics
```typescript theme={null}
interface Statistics {
total_balance: number;
total_deposits: number;
total_users: number;
total_transactions: number;
total_apr: number;
liquidity_distribution: LiquidityDistribution;
}
```
### TVLResponse
```typescript theme={null}
interface TVLResponse {
tvl: number;
}
```
### TokenInfo
```typescript theme={null}
interface TokenInfo {
address: string;
symbol: string;
decimals: number;
balance: number;
current_price: number;
}
```
### TokensResponse
```typescript theme={null}
interface TokensResponse {
tokens: TokenInfo[];
}
```
***
## Agent Enums
### AgentStatus
```typescript theme={null}
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',
}
```
### TxAction
```typescript theme={null}
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',
}
```
### TxStatus
```typescript theme={null}
enum TxStatus {
UNKNOWN = 'unknown',
PENDING = 'pending',
APPROVED = 'approved',
CANCELLED = 'cancelled',
FAILED = 'failed',
}
```
### SortOrder
```typescript theme={null}
enum SortOrder {
DATE_ASC = 'date_asc',
DATE_DESC = 'date_desc',
}
```
### Order
```typescript theme={null}
enum Order {
ASC = 'asc',
DESC = 'desc',
}
```
### Period
```typescript theme={null}
enum Period {
ALL = 'all',
DAY = 'day',
}
```
### ExecutionStatus
```typescript theme={null}
enum ExecutionStatus {
RUNNING = 'running',
FAILED = 'failed',
SUCCESS = 'success',
}
```
***
## Optimizer Types
### OptimizeOptions
```typescript theme={null}
interface OptimizeOptions {
chain?: Chain;
token: Address;
capital: string;
currentAllocations: Record;
protocols: string[];
constraints?: ConstraintConfig[];
wallet?: Address;
}
```
### OptimizeResponse
```typescript theme={null}
interface OptimizeResponse {
optimization_result: OptimizationResult;
action_plan: ActionDetail[];
calldata: CalldataInfo[];
}
```
### OptimizationResult
```typescript theme={null}
interface OptimizationResult {
allocations: ProtocolAllocation[];
total_costs: number;
weighted_apr_initial: number;
weighted_apr_final: number;
apr_improvement: number;
gas_estimate_usd?: number;
break_even_days?: number;
}
```
### ProtocolAllocation
```typescript theme={null}
interface ProtocolAllocation {
protocol: string;
allocation: string;
apr: number;
}
```
### ActionDetail
```typescript theme={null}
interface ActionDetail {
action_type: 'deposit' | 'withdraw';
protocol: string;
amount: string;
underlying_amount?: string;
}
```
### CalldataInfo
```typescript theme={null}
interface CalldataInfo {
contract_address: string;
function_name: string;
parameters: string[];
value: string;
protocol: string;
description: string;
}
```
### WalletConstraints
```typescript theme={null}
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',
}
```
### ConstraintConfig (Optimizer)
Imported as `OptimizerConstraintConfig` to distinguish from the agent variant.
```typescript theme={null}
interface ConstraintConfig {
kind: WalletConstraints;
params: Record;
}
```
***
## Paginator Types
### Paginator\
Async-iterable paginator returned by collection methods. See [Paginator reference](/sdk-reference/paginator).
```typescript theme={null}
class Paginator implements AsyncIterable {
async *[Symbol.asyncIterator](): AsyncIterableIterator;
async page(num: number, opts?: { limit?: number }): Promise>;
async first(count?: number): Promise;
}
```
### PaginatedResponse\
```typescript theme={null}
interface PaginatedResponse {
items: T[];
total: number;
page: number;
limit: number;
hasMore: boolean;
}
```
### PageFetcher\
Internal type used by the `Paginator` constructor.
```typescript theme={null}
type PageFetcher = (
page: number,
limit: number,
) => Promise>;
```
***
## Error Classes
### GizaError
Base class for all SDK errors. Extends `Error`.
```typescript theme={null}
class GizaError extends Error {
constructor(message: string);
}
```
### ValidationError
Thrown on invalid input (bad addresses, missing fields, invalid values).
```typescript theme={null}
class ValidationError extends GizaError {
constructor(message: string);
}
```
### NotImplementedError
Thrown when calling a feature that is not yet implemented.
```typescript theme={null}
class NotImplementedError extends GizaError {
constructor(message: string);
}
```
### GizaAPIError
Thrown when the Giza API returns a non-2xx response.
```typescript theme={null}
class GizaAPIError extends GizaError {
readonly statusCode: number;
readonly responseData: unknown;
readonly requestUrl?: string;
readonly requestMethod?: string;
readonly friendlyMessage: string;
constructor(
message: string,
statusCode: number,
responseData?: unknown,
requestUrl?: string,
requestMethod?: string,
);
static fromResponse(
statusCode: number,
responseData: unknown,
requestUrl?: string,
requestMethod?: string,
): GizaAPIError;
toJSON(): object;
}
```
### TimeoutError
Thrown when a request or polling operation exceeds its timeout.
```typescript theme={null}
class TimeoutError extends GizaError {
constructor(timeout: number, message?: string);
}
```
### NetworkError
Thrown on network connectivity failures (DNS resolution, connection refused, etc.).
```typescript theme={null}
class NetworkError extends GizaError {
constructor(message: string);
}
```
***
## Constants
### DEFAULT\_AGENT\_ID
Default agent identifier used for smart account creation.
```typescript theme={null}
const DEFAULT_AGENT_ID = 'giza-app';
```
### DEFAULT\_TIMEOUT
Default HTTP request timeout in milliseconds.
```typescript theme={null}
const DEFAULT_TIMEOUT = 45000;
```
### CHAIN\_NAMES
Map of chain IDs to human-readable names.
```typescript theme={null}
const CHAIN_NAMES: Record = {
[-1]: 'Devnet',
[1]: 'Ethereum',
[137]: 'Polygon',
[999]: 'Chain 999',
[8453]: 'Base',
[9745]: 'Chain 9745',
[11155111]: 'Sepolia',
[42161]: 'Arbitrum',
[84532]: 'Base Sepolia',
};
```