Building Custom Functions for Virtuals Protocol Using the SimpleHash API
The Virtuals protocol has taken the blockchain space by storm, enabling developers to create autonomous AI agents that interact with blockchain data like never before. Unlike other protocols such as ElizaOS, which focus on broader conversational or productivity use cases, Virtuals stands out by offering a Sandbox UI for streamlined development and attaching a token to each agent. This token utilizes trading fees to access its stack and post on X, making it uniquely suited for the blockchain community.
Here are a few examples of what Virtuals agents can do:
- NFT Curation: analyze collections, spot price trends, and track rarity data.
- Quant Trading: provide technical analysis and actionable market insights.
- DeFi Strategy: identify optimal yield opportunities across protocols.
- Portfolio Management: track and rebalance token holdings, acting as autonomous fund managers.
At the core of their functionality lies the ability to use custom functions—tailored tools that leverage APIs for specific tasks. This guide walks you through creating custom functions for Virtuals using SimpleHash’s Universal Token API, which provides:
- Multi-chain token and NFT data
- Real-time DEX prices and volume metrics
- Historical transactions and metadata
- Ownership tracking and rarity insights
Let’s dive into building a custom function step by step.
Step-by-Step Guide: Creating a Custom Function in Virtuals Sandbox
The Sandbox is the central development environment within Virtuals, enabling you to define and test your custom functions. It's where you can configure API integrations, set up response templates, and validate your agent's behavior before deploying it live. You can try it for yourself at https://game-lite.virtuals.io/.
Step 1: Define the Function Name
Start with a descriptive name that clearly explains the purpose. For example:
get_token_balances
This tells the agent the function retrieves token balances for wallet addresses.
Step 2: Add a Function Description
Provide a brief explanation for when and why the function should be used:
Fetches all fungible token balances for specified wallet addresses, ordered by last transferred date.
Step 3: Specify Arguments
Define the inputs required for the function. In this case:
- wallet_addresses (required): Array of wallet addresses to query.
- chains (required): Array of chain identifiers (e.g., ethereum, polygon, base).
Step 4: Configure the API Endpoint
Set up the API call to SimpleHash. Here's an example configuration:
HTTP Method: GET
API URL: https://api.simplehash.com/api/v0/fungibles/balances?chains={{chains}}&wallet_addresses={{wallet_addresses}}&include_fungible_details=1&include_prices=1&count=0&limit=1&order_by=last_transferred_date__desc&include_native_tokens=1
Headers:
{
"X-API-KEY": "YOUR_API_KEY",
"accept": "application/json"
}
Step 5: Define Response Templates
Custom functions use Mustache templates for parsing API responses. A Mustache template allows you to dynamically format API data into clear, readable outputs. For example, given this sample API response:
{
"data": {
"messages": [
{ "content": "hello world!" },
{ "content": "hello world!" }
]
}
}
You can define your success feedback as:
The messages fetched are {{#response.data.messages}}{{content}}{{/response.data.messages}}.
You can check if your response fits the Mustache template using an online checker like this one.
Now, let's go back to our example. For success and error cases:
Success Feedback Template
{{#response.fungibles}}
TOKEN: {{name}} ({{symbol}})
BALANCE: {{queried_wallet_balances.[0].quantity_string}}
{{#if prices.[0]}}PRICE: ${{prices.[0].value_usd_string}}{{/if}}
{{#if queried_wallet_balances.[0].value_usd_string}}VALUE: ${{queried_wallet_balances.[0].value_usd_string}}{{/if}}
CHAIN: {{chain}}
LAST TRANSFER: {{queried_wallet_balances.[0].last_transferred_date}}
{{#if fungible_details}}
DECIMALS: {{fungible_details.decimals}}
HOLDERS: {{fungible_details.holder_count}}
{{/if}}
================
{{/response.fungibles}}
{{#if response.next_cursor}}
NEXT PAGE: {{response.next_cursor}}
{{/if}}
Error Feedback Template
Error fetching token balances.
Status: {{status}}
Message: {{message}}
For a wallet querying balances on Ethereum, Polygon, and Base, the response might look like this:
TOKEN: AAVE (AAVE)
BALANCE: 263183000000000000
PRICE: $0.000004082
VALUE: $10743.51
CHAIN: base
LAST TRANSFER: 2025-01-05T07:57:27Z
DECIMALS: 8
HOLDERS: 195349
================
TOKEN: Focai (Focai)
BALANCE: 2482570000000000
PRICE: $0.0003897
VALUE: $9673.74
CHAIN: base
LAST TRANSFER: 2025-01-04T11:11:29Z
DECIMALS: 8
HOLDERS: 168399
================
Step 6: Test and Validate
Before deploying your agent from the Sandbox UI using the custom function:
- Verify arguments are correctly injected.
- Ensure the API endpoint is functional.
- Test the response format against real data.
- Confirm error handling works as expected by running simulations in the sandbox environment.
Best Practices for Building Effective Functions
Data Handling
- Use clear response formats and document all fields.
- Include examples to clarify relationships between data points.
Error Handling
- Define retry strategies and timeout limits.
- Use clear error messages for troubleshooting.
Rate Limiting
- Document API call frequency limits.
- Implement pagination and batching strategies.
State Management
- Track relevant IDs, offsets, or cursors.
- Persist important session data when necessary.
Custom functions empower Virtuals agents to tackle a wide range of blockchain-specific tasks. Whether you need to analyze NFT trends, execute DeFi strategies, or manage token portfolios, SimpleHash’s Universal Token API offers the data foundation for intelligent automation.
These functions shine in the four key use cases outlined earlier, but they can also serve as a foundation for building virtually anything you envision. Their utility extends far beyond these specific examples:
- NFT Curation: By querying NFTs by Wallet—the equivalent NFT endpoint to token balances—you can analyze and adapt to your evolving NFT portfolio, calculate their values, showcase collections, or track collection trends with precision. Building an agent with these insights allows users to make well-informed decisions in the dynamic NFT market.
- Quant Trading: Leverage a combination of our real-time charting endpoints, such as OLHC (candlestick), swaps & transfers, and moving average endpoint, to build out a quant trading agent that informs precise market decisions by using technical analysis.
- DeFi Strategy: Aggregate liquidity metrics from a variety of liquidity pools for a given token using SimpleHash’s Get Token and Prices endpoint to optimize yield opportunities.
- Portfolio Management: Enable agents to rebalance holdings based on live token data using the function in the example.
What’s Next?
Are you ready to build your first AI agent? Try creating a custom function today and explore how SimpleHash’s data can power your agentic journey!
For more information on our fungible token, native token, and NFT endpoints – visit our documentation.