Developer Advanced

How to Build a DeFi Trading Agent with Eliza and FarmDash Signal Architect

A complete developer guide to giving your Eliza framework AI agent the ability to execute cross-chain and single-chain token swaps using the FarmDash zero-custody Signal Architect API.

F
FarmDash Pioneers
Updated Feb 26, 2026 · 76 days ago
>>> VIEW LIVE FARMDASH API TRAIL HEAT <<<

TLDR: Autonomous agents built on frameworks like Eliza need secure, reliable execution layers to trade tokens. The FarmDash Signal Architect API provides a zero-custody routing layer that aggregates 0x and Li.Fi liquidity natively. By implementing a simple FarmDashSwapTool, your Eliza agent can request quotes, sign transactions via EIP-191, and execute trades autonomously without handing over custody of its private keys.

If you are building an AI agent that operates on-chain, one of the first capabilities you need is token swapping. Whether your agent is trading based on sentiment analysis, executing arbitrage, or managing a portfolio, it needs a way to move assets efficiently.

This guide walks you through integrating the FarmDash Signal Architect API into the Eliza framework to give your agent native DeFi trading capabilities.

What is the FarmDash Signal Architect?

The FarmDash Signal Architect is a zero-custody Agent-to-Agent fee routing layer. It exposes an LLM-friendly REST API that:

  1. Aggregates Liquidity: Automatically routes trades through 0x (for single-chain) and Li.Fi (for cross-chain).
  2. Maintains Zero Custody: FarmDash never holds your agent's private keys or funds. It returns standard EVM calldata that your agent signs locally.
  3. Optimizes Execution: Ensures the lowest slippage and gas costs.
Feature Description FarmDash Advantage
Authentication EIP-191 Signatures No API keys required for agents. Cryptographic proof of intent.
Routing 0x, Li.Fi, Alchemy x402 Best price execution across 60+ chains.
Custody Model Return Calldata Agent retains total control of funds and private keys.
Replay Protection 60s Nonce Window Prevents malicious interception of agent API requests.

Step 1: Providing Context to the Agent

Before writing code, your agent needs to understand how to use the API. If you are using Eliza or LangChain, you should add the FarmDash OpenAPI spec or context file to the agent's system prompt or tool descriptions.

You can point your agent directly to the machine-readable spec: OpenAPI Spec: https://www.farmdash.one/agents/swap/openapi.yaml

Or drop the contents of the farmdash-swap-tool.md context file into your agent's knowledge base.

For OpenClaw Agents

If you are running an OpenClaw agent, you don't need to write custom code. FarmDash publishes raw OpenClaw skill files you can drop into your workspace today:

  • https://www.farmdash.one/openclaw-skills/farmdash-signal-architect/SKILL.md
  • https://www.farmdash.one/openclaw-skills/farmdash-trail-intelligence/SKILL.md

ClawHub registry installation is not live yet, so use the raw skill file or clone the repository:

git clone https://github.com/Parmasanandgarlic/farmdashbeta.git
# then copy src/content/openclaw-skills/farmdash-signal-architect into your agent workspace

The skill automatically injects the OpenAPI spec and teaches your agent how to sign EIP-191 payloads.

Step 2: Creating the Eliza Action Tool

In the Eliza framework, capabilities are added via Actions. We need to create an Action that allows the agent to call the /api/agents/swap endpoint.

Here is a simplified TypeScript implementation of a FarmDashSwapTool:

import { Action, IAgentRuntime, Memory, State } from "@elizaos/core";
import { privateKeyToAccount } from "viem/accounts";

export const farmDashSwapAction: Action = {
    name: "EXECUTE_TOKEN_SWAP",
    similes: ["SWAP_TOKENS", "TRADE_CRYPTO", "EXCHANGE_ASSETS"],
    description: "Executes a token swap on any EVM chain using the FarmDash Signal Architect API.",
    
    validate: async (runtime: IAgentRuntime, message: Memory) => {
        // Ensure agent has a private key configured
        return !!runtime.getSetting("EVM_PRIVATE_KEY");
    },

    handler: async (runtime: IAgentRuntime, message: Memory, state: State) => {
        // 1. Extract swap parameters from the message content.
        // In practice you would run an LLM extraction step first (e.g. using
        // runtime.composeState + a structured output prompt) to parse the user's
        // intent into typed swap fields. Here we assume that step is already done
        // and the results are available on state.
        const { fromChainId, toChainId, fromToken, toToken, fromAmount } = state.swapDetails as {
            fromChainId: number; toChainId: number;
            fromToken: string;   toToken: string;
            fromAmount: string;  // wei string, e.g. "1000000" for 1 USDC
        };
        
        // 2. Setup the Agent's Wallet
        const privateKey = runtime.getSetting("EVM_PRIVATE_KEY");
        const account = privateKeyToAccount(privateKey as `0x${string}`);
        const nonce = Date.now().toString();

        // 3. Construct the EIP-191 Payload for FarmDash Auth
        const payload = [
            'FARMDASH_SWAP', 
            fromChainId, toChainId,
            fromToken.toLowerCase(),
            toToken.toLowerCase(),
            fromAmount,
            account.address.toLowerCase(),
            account.address.toLowerCase(), // sending back to self
            nonce
        ].join(':');

        // 4. Sign the Payload
        const signature = await account.signMessage({ message: payload });

        // 5. Request Calldata from FarmDash Signal Architect
        const res = await fetch('https://www.farmdash.one/api/agents/swap', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                fromChainId, toChainId,
                fromToken, toToken,
                fromAmount,
                agentAddress: account.address,
                toAddress: account.address,
                nonce, 
                signature
            })
        });

        if (!res.ok) {
            const err = await res.text().catch(() => res.statusText);
            throw new Error(`Swap routing failed (${res.status}): ${err}`);
        }

        const quote = await res.json();

        // 6. Execute the Transaction Locally.
        // quote.txData contains { to, data, value, chainId } — a standard EVM
        // transaction object ready to be signed and broadcast. Use your viem
        // wallet client (or ethers.js signer) to send it. Example with viem:
        //
        //   import { createWalletClient, http } from 'viem';
        //   import { base } from 'viem/chains';
        //   const walletClient = createWalletClient({ account, chain: base, transport: http() });
        //   const txHash = await walletClient.sendTransaction(quote.txData);
        //
        // The example below uses a runtime helper; replace with your own wallet client.
        const txHash = await executeTransaction(runtime, quote.txData);

        return `Swap executed successfully. Hash: ${txHash}`;
    },
    
    examples: [
        [
            { user: "user1", content: { text: "Swap 1 ETH to USDC on Base" } },
            { user: "agent", content: { text: "I will execute that swap via FarmDash.", action: "EXECUTE_TOKEN_SWAP" } }
        ]
    ]
};

How does the EIP-191 Authentication work?

Unlike traditional APIs that require hardcoded API keys (which are dangerous to give to autonomous agents), the Signal Architect API uses cryptographic signatures.

The agent constructs a colon-delimited string of its requested swap parameters and signs it using its private key (personal_sign). FarmDash verifies this signature on the server to ensure the request genuinely came from the wallet address it claims to represent.

The inclusion of the nonce (a timestamp) ensures that if the API request is intercepted over the network, it cannot be replayed later.

How Can High-Volume Agents Unlock Fee Discounts?

The Signal Architect supports volume-based fee discounts. Agents that know the approximate USD value of their trade can pass a volumeHintUSD field to receive lower fees:

Trade Volume (USD) Fee Rate
Under $10,000 75 bps (0.75%)
$10,000 - $99,999 35 bps (0.35%)
$100,000+ 25 bps (0.25%)

To use this in your Eliza Action, add the field to the request body:

body: JSON.stringify({
    fromChainId, toChainId,
    fromToken, toToken, fromAmount,
    agentAddress: account.address,
    toAddress: account.address,
    nonce, signature,
    volumeHintUSD: 50000 // agent's USD estimate of this trade
})

How Can Agents Use the @farmdash/agent-kit SDK?

For TypeScript agents that want a typed client with built-in retry and caching instead of raw fetch calls, use the source package in this repo:

git clone https://github.com/Parmasanandgarlic/farmdashbeta.git
cd farmdashbeta
npm install ./agent-kit

The SDK wraps all read endpoints (getProtocols, getQuote, getSwapHistory, getRevenueMetrics) with automatic retry, ETag caching, and Dust Storm resilience (graceful empty responses on network failure instead of thrown exceptions).

import { FarmDashClient } from '@farmdash/agent-kit';

const client = new FarmDashClient();

// Preview a quote before signing
const quote = await client.getQuote({
  fromChainId: 8453, toChainId: 8453,
  fromToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  toToken: '0x4ed4e862860bef6f5bc2b489d12a64703a110a12',
  fromAmount: '1000000',
});

if (quote.ok) {
  console.log(`Estimated output: ${quote.data.estimatedOutput}`);
  console.log(`Fee: ${quote.data.feeBps} bps ($${quote.data.feeAmountUSD})`);
}

For the full SDK reference, see the Signal Architect Complete Reference.

Why use FarmDash over calling 0x or Li.Fi directly?

While an agent could theoretically integrate with underlying liquidity aggregators directly, the FarmDash API simplifies the abstraction layer for LLMs.

  1. Unified Interface: The agent doesn't need to know the difference between Li.Fi's API schema and 0x's API schema. It uses one unified JSON schema for all chains and protocols.
  2. Built-in Fallbacks: If a specific chain is degraded, FarmDash automatically reroutes.
  3. No Key Management: Agents don't need to hold or manage 3rd party API keys in their .env files to get decent rate limits. FarmDash handles the high-capacity rate limits under the hood.

Explore the API Dashboard

READY TO HIT THE TRAIL?

Connect your wagon to the FarmDash terminal and track your Pioneer Pace across 80+ live protocols.

OPEN TERMINAL