From 32756d2af05d37407b8abc62f2b149ed00eab495 Mon Sep 17 00:00:00 2001 From: Mikers Date: Wed, 16 Jul 2025 07:50:00 -1000 Subject: [PATCH 1/9] add eliza and vercel drafts --- docs/competitions/guides/eliza.mdx | 253 ++++++++++++++++++++++++++++ docs/competitions/guides/meta.json | 3 +- docs/competitions/guides/vercel.mdx | 247 +++++++++++++++++++++++++++ 3 files changed, 502 insertions(+), 1 deletion(-) create mode 100644 docs/competitions/guides/eliza.mdx create mode 100644 docs/competitions/guides/vercel.mdx diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx new file mode 100644 index 0000000..ce0bd80 --- /dev/null +++ b/docs/competitions/guides/eliza.mdx @@ -0,0 +1,253 @@ +--- +title: Five‑Minute Eliza Trader +description: Rapid guide to scaffold an Eliza agent and execute a sandbox trade on the Recall Network. +--- + +# Overview + +This tutorial shows how to spin up a fully functional **Eliza‑based trading agent** and place a sandbox order on the Recall Network in about five minutes. You will: + +1. Scaffold a new Eliza project. +2. Add a Recall trade tool. +3. Create a minimal trading agent. +4. Register a simple workflow. +5. Place your first order through the Eliza dashboard. + +The guide targets TypeScript developers familiar with Node 20 + but new to Eliza or Recall. + +--- + +## Prerequisites + +| Requirement | Minimum version | Purpose | +| -------------------------- | --------------- | ------------------------------------ | +| **Node.js** | 20 + | Runtime for the bot | +| **npm** | Comes with Node | Package manager | +| **OpenAI API key** | – | LLM reasoning for the Eliza agent | +| **Recall API key & URL** | – | Access to trading endpoints | + + +Create a .env file in the project root to store API keys locally and keep them out of source control. + + +--- + +## 1. Scaffold the Project + +### 1.1 Create the workspace + +```bash copy +npm create eliza@latest recall-eliza-bot +cd recall-eliza-bot +```` + +Select **blank** when prompted for a starter template. + +### 1.2 Install dependencies + +```bash copy +npm install axios axios-retry +``` + +### 1.3 Add environment secrets + +```dotenv filename=".env" copy +OPENAI_API_KEY=sk-... +RECALL_API_KEY=rk-... +RECALL_API_URL=https://api.sandbox.competitions.recall.network +``` + +--- + +## 2. Add the Recall Trade Tool + +Create `src/eliza/tools/recall-trade.ts`: + +```ts filename="src/eliza/tools/recall-trade.ts" showLineNumbers copy +import { createTool } from '@eliza/core/tools'; +import axios from 'axios'; +import { z } from 'zod'; + +export const recallTrade = createTool({ + id: 'recall-trade', + description: 'Execute a spot trade on the Recall Network', + inputSchema: z.object({ + fromToken: z.string().describe('ERC‑20 address'), + toToken: z.string().describe('ERC‑20 address'), + amount: z.string().describe('Human‑readable amount in FROM token'), + reason: z.string().optional(), + }), + outputSchema: z.object({ + txHash: z.string(), + status: z.string(), + }), + execute: async ({ fromToken, toToken, amount, reason }) => { + const { RECALL_API_URL, RECALL_API_KEY } = process.env; + + const { data } = await axios.post( + `${RECALL_API_URL}/api/trade/execute`, + { fromToken, toToken, amount, reason }, + { + headers: { Authorization: `Bearer ${RECALL_API_KEY}` }, + timeout: 30_000, + }, + ); + + return { txHash: data.txHash, status: data.status }; + }, +}); +``` + +--- + +## 3. Create the Trading Agent + +Create `src/eliza/agents/recall-agent.ts`: + +```ts filename="src/eliza/agents/recall-agent.ts" showLineNumbers copy +import { openai } from '@ai-sdk/openai'; +import { Agent } from '@eliza/core/agent'; +import { recallTrade } from '../tools/recall-trade'; + +export const recallAgent = new Agent({ + name: 'Recall Agent', + instructions: ` +You are a Recall competition trading agent. + +• Submit exactly one trade when invoked. +• Buy 10 USDC‑worth of WETH regardless of market conditions. +• Use the recall‑trade tool with: + fromToken = USDC (0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) + toToken = WETH (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) + amount = "10" +• Add a short reason like "tutorial trade". +`, + model: openai('gpt-4o-mini'), + tools: { recallTrade }, +}); +``` + +--- + +## 4. Build the Workflow + +Create `src/eliza/workflows/recall-workflow.ts`: + +```ts filename="src/eliza/workflows/recall-workflow.ts" showLineNumbers copy +import { createStep, createWorkflow } from '@eliza/core/workflows'; +import { z } from 'zod'; + +const tradeStep = createStep({ + id: 'run-recall-agent', + description: 'Invoke the Recall agent once', + inputSchema: z.void(), + outputSchema: z.object({ + result: z.string(), + }), + execute: async ({ mastra }) => { + // "mastra" here refers to the Eliza runtime context + const agent = mastra?.getAgent('recallAgent'); + if (!agent) throw new Error('recallAgent not found'); + + const response = await agent.stream([ + { role: 'user', content: 'Make a trade now.' }, + ]); + + let text = ''; + for await (const chunk of response.textStream) { + text += chunk; + } + + return { result: text }; + }, +}); + +const recallWorkflow = createWorkflow({ + id: 'recall-workflow', + outputSchema: z.object({ + result: z.string(), + }), +}).then(tradeStep); + +recallWorkflow.commit(); + +export { recallWorkflow }; +``` + +--- + +## 5. Register Agent and Workflow + +Edit `src/index.ts`: + +```ts filename="src/index.ts" showLineNumbers copy +import { Eliza } from '@eliza/core/eliza'; +import { PinoLogger } from '@eliza/loggers'; +import { LibSQLStore } from '@eliza/libsql'; +import { recallWorkflow } from './eliza/workflows/recall-workflow'; +import { recallAgent } from './eliza/agents/recall-agent'; + +export const eliza = new Eliza({ + workflows: { recallWorkflow }, + agents: { recallAgent }, + storage: new LibSQLStore({ + url: ':memory:', + }), + logger: new PinoLogger({ + name: 'Eliza', + level: 'info', + }), +}); +``` + +--- + +## 6. Test in the Eliza Dashboard + +### 6.1 Start the server + +```bash copy +npm run dev +``` + +### 6.2 Open the dashboard + +Navigate to: + +``` +http://localhost:4111/agents/recallAgent/chat +``` + +### 6.3 Place a trade + +Type the following message: + +``` +Buy $10 worth of Ethereum +``` + +The agent processes the request, uses the `recallTrade` tool, and executes a sandbox order on Recall. A confirmation appears in the chat, for example: + +> Trade executed: 0xabc123… (status: filled) + +--- + +## 7. Troubleshooting + +| Symptom or message | Likely cause | Solution | +| ------------------------- | -------------------- | ----------------------------------- | +| `401 Unauthorized` | Invalid Recall key | Verify `RECALL_API_KEY` in `.env` | +| `429 Too Many Requests` | Rate limit hit | Allow axios‑retry to back‑off | +| “Not enough cash/balance” | Sandbox faucet empty | Request USDC from the Recall faucet | + +--- + +## 8. Next Steps + +* **Enhance prompts** to include dynamic market logic. +* **Add memory** with LibSQL or Redis to track open positions. +* **Deploy** to Fly.io or Docker Swarm for production use. +* **Enter a Recall competition** once your key is sandbox‑verified. + +Your Eliza-powered bot is now live and capable of trading on Recall in under five minutes. + diff --git a/docs/competitions/guides/meta.json b/docs/competitions/guides/meta.json index dc98fcb..64f7fd8 100644 --- a/docs/competitions/guides/meta.json +++ b/docs/competitions/guides/meta.json @@ -1,4 +1,5 @@ { "title": "Join competitions", - "pages": ["register", "setup", "mcp", "trading", "portfolio-manager-tutorial", "faq"] + "pages": ["register", "setup", "mcp", "trading", "eliza", + "vercel","portfolio-manager-tutorial", "faq"] } diff --git a/docs/competitions/guides/vercel.mdx b/docs/competitions/guides/vercel.mdx new file mode 100644 index 0000000..3dbdd85 --- /dev/null +++ b/docs/competitions/guides/vercel.mdx @@ -0,0 +1,247 @@ +--- +title: Serverless Trader with Next.js 13 & Recall +description: Guide to build and deploy a Recall trading bot using Next.js 13, Vercel Functions, and the Vercel AI SDK. +--- + +# Introduction + +This tutorial demonstrates how to combine **Next.js 13**, **Vercel Functions**, and the **Vercel AI SDK** to create a fully serverless trading bot that submits orders to the Recall Network. You will: + +1. Scaffold a TypeScript Next.js 13 application. +2. Implement an edge function that decides and places trades. +3. Build a lightweight React UI using the AI SDK’s `useChat` hook. +4. Test locally, then deploy with a single `vercel --prod`. + +The result is a production‑ready service that streams AI output, executes sandbox trades, and runs entirely on Vercel’s global edge. + +--- + +## 1. Prerequisites + +| Requirement | Minimum version | Purpose | +| ----------------------- | --------------- | ------------------------------------ | +| **Node.js** | 20 + | Local Next.js runtime | +| **npm** | Comes with Node | Package manager | +| **Vercel CLI** | 34 + | Deploy & manage environment vars | +| **OpenAI API key** | – | LLM reasoning via AI SDK | +| **Recall API key & URL**| – | Access to trading endpoints | +| **Vercel account** | – | Hosting & edge functions | + +--- + +## 2. Project Setup + +### 2.1 Create the Next.js app + +```bash copy +npx create-next-app@latest recall-vercel-bot --ts --app --eslint --tailwind --src-dir +cd recall-vercel-bot +```` + +### 2.2 Install runtime packages + +```bash copy +npm install ai axios axios-retry +``` + +--- + +## 3. Environment Variables + +Add variables locally in `.env.local` (automatically git‑ignored): + +```dotenv filename=".env.local" copy +OPENAI_API_KEY=sk-... +RECALL_API_KEY=rk-... +RECALL_API_URL=https://api.sandbox.competitions.recall.network +``` + +Set them in Vercel later: + +```bash +vercel env add OPENAI_API_KEY +vercel env add RECALL_API_KEY +vercel env add RECALL_API_URL +``` + +--- + +## 4. Edge Function: `route.ts` + +Create `src/app/api/trade/route.ts`: + +```ts filename="src/app/api/trade/route.ts" showLineNumbers copy +import { OpenAIStream, StreamingTextResponse } from 'ai'; +import OpenAI from 'openai'; +import axios from 'axios'; + +export const runtime = 'edge'; // Next.js Edge Function + +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +export async function POST(req: Request) { + const { prompt } = await req.json(); + + // 1. Use OpenAI to reason about a trade + const completion = await openai.chat.completions.create({ + model: 'gpt-4o-mini', + stream: true, + messages: [ + { + role: 'system', + content: + `Decide whether to buy WETH with 10 USDC on Recall.\n` + + `Return JSON with fields {execute: boolean, reason: string}.`, + }, + { role: 'user', content: prompt }, + ], + }); + + // 2. Stream tokens back to the UI + const stream = OpenAIStream(completion, { + async onFinal(chunk) { + try { + const decision = JSON.parse(chunk); + if (!decision.execute) return; + + // 3. Execute trade on Recall + const { data } = await axios.post( + `${process.env.RECALL_API_URL}/api/trade/execute`, + { + fromToken: + '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC + toToken: + '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH + amount: '10', + reason: decision.reason, + }, + { + headers: { + Authorization: `Bearer ${process.env.RECALL_API_KEY}`, + }, + timeout: 30_000, + } + ); + + console.log('Recall trade txHash:', data.txHash); + } catch (err) { + console.error('Trade execution failed:', err); + } + }, + }); + + return new StreamingTextResponse(stream); +} +``` + +--- + +## 5. React Front‑End + +Create `src/app/page.tsx`: + +```tsx filename="src/app/page.tsx" showLineNumbers copy +'use client'; + +import { useChat } from 'ai/react'; +import { useState } from 'react'; + +export default function Home() { + const { messages, input, handleInputChange, handleSubmit, isLoading } = + useChat({ + api: '/api/trade', + }); + + const [status, setStatus] = useState(''); + + return ( +
+

+ Recall Serverless Trader +

+ +
{ + handleSubmit(e).then(() => setStatus('Request sent.')); + }} + className="flex gap-2" + > + + +
+ + {status &&

{status}

} + +
+ {messages.map((m) => ( +
+ {m.role}: {m.content} +
+ ))} +
+
+ ); +} +``` + +--- + +## 6. Local Test + +```bash copy +npm run dev +``` + +Open `http://localhost:3000`, ask “Should we buy now?”. +If the model responds with `{"execute":true,…}`, the edge function streams the decision and places a sandbox trade—visible in your console and the Recall dashboard. + +--- + +## 7. Deploy to Vercel + +```bash copy +vercel --prod +``` + +Vercel picks up environment variables, builds the Next.js app, and deploys edge functions globally. The production URL is printed at the end of the deployment. + +--- + +## 8. Validate in Recall + +1. Log in to the Recall dashboard. +2. Confirm the sandbox order appears in **Orders → Sandbox**. +3. Your API key is now whitelisted for live competitions. + +--- + +## 9. Troubleshooting + +| Message / symptom | Likely cause | Resolution | +| --------------------------- | -------------------------- | ----------------------------------------------- | +| `401 Unauthorized` | Invalid Recall key | Regenerate key and re‑add in Vercel dashboard | +| `429 Too Many Requests` | Recall rate limit | Axios‑retry handles back‑off automatically | +| Edge function build error | Unsupported Node API | Keep only Web API–compatible code in `route.ts` | +| “Missing env var” at deploy | Variable not set in Vercel | `vercel env add ` before deploy | + +--- + +## 10. Scalability Notes + +* **Vercel Cron**: schedule `/api/trade` POSTs nightly for back‑tests. +* **Edge Middleware**: add JWT validation to protect the endpoint. +* **Observability**: forward AI latency and trade metrics to Vercel Analytics. + +Your serverless trading bot is live—powered by Next.js 13, Vercel Functions, and the AI SDK, with all orders routed securely through Recall’s sandbox environment. From 9022e8ad890f4b47b7f84f743edea55b36e82db7 Mon Sep 17 00:00:00 2001 From: Mikers Date: Wed, 16 Jul 2025 10:48:39 -1000 Subject: [PATCH 2/9] update --- docs/competitions/guides/eliza.mdx | 119 +++++++++++++++++-------- docs/competitions/guides/vercel.mdx | 132 +++++++++++++++++++++------- 2 files changed, 181 insertions(+), 70 deletions(-) diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index ce0bd80..a8d89c1 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -3,53 +3,55 @@ title: Five‑Minute Eliza Trader description: Rapid guide to scaffold an Eliza agent and execute a sandbox trade on the Recall Network. --- -# Overview +Welcome! Let’s go from zero to your first Eliza-powered trading bot on Recall—in under five minutes. 🚀 +By the end, you’ll have placed a real (test) trade, seen your agent in action, and unlocked the door to deeper automation. Here’s the roadmap: -This tutorial shows how to spin up a fully functional **Eliza‑based trading agent** and place a sandbox order on the Recall Network in about five minutes. You will: +1. Scaffold a new Eliza project +2. Add a Recall trade tool +3. Create a minimal trading agent +4. Register a workflow +5. Place your first order through the Eliza dashboard -1. Scaffold a new Eliza project. -2. Add a Recall trade tool. -3. Create a minimal trading agent. -4. Register a simple workflow. -5. Place your first order through the Eliza dashboard. - -The guide targets TypeScript developers familiar with Node 20 + but new to Eliza or Recall. +This guide is perfect for TypeScript developers comfy with Node 20+ but new to Eliza or Recall. If that’s you—let’s dive in! --- ## Prerequisites -| Requirement | Minimum version | Purpose | -| -------------------------- | --------------- | ------------------------------------ | -| **Node.js** | 20 + | Runtime for the bot | -| **npm** | Comes with Node | Package manager | -| **OpenAI API key** | – | LLM reasoning for the Eliza agent | -| **Recall API key & URL** | – | Access to trading endpoints | +| Requirement | Minimum version | Purpose | +|------------------------|----------------|--------------------------------------| +| **Node.js** | 20+ | Runtime for the bot | +| **npm** | Comes with Node| Package manager | +| **OpenAI API key** | – | LLM reasoning for the Eliza agent | +| **Recall API key & URL**| – | Access to trading endpoints | -Create a .env file in the project root to store API keys locally and keep them out of source control. +Don’t have your keys yet? +- Get an OpenAI API key +- Register for a Recall API key +Store all keys in a .env file at the project root—keep them out of source control! --- ## 1. Scaffold the Project -### 1.1 Create the workspace +Ready? Let’s spin up your workspace: ```bash copy npm create eliza@latest recall-eliza-bot cd recall-eliza-bot ```` -Select **blank** when prompted for a starter template. +When prompted, choose the **blank** template. -### 1.2 Install dependencies +**Next, install a couple of helpers:** ```bash copy npm install axios axios-retry ``` -### 1.3 Add environment secrets +Now set up your secrets: ```dotenv filename=".env" copy OPENAI_API_KEY=sk-... @@ -57,10 +59,16 @@ RECALL_API_KEY=rk-... RECALL_API_URL=https://api.sandbox.competitions.recall.network ``` + +Your `.env` file keeps credentials safe and separate from your code. Pro tip: Always add `.env` to `.gitignore`! + + --- ## 2. Add the Recall Trade Tool +Time to teach your bot how to trade! In Eliza, “tools” are modular skills an agent can use. + Create `src/eliza/tools/recall-trade.ts`: ```ts filename="src/eliza/tools/recall-trade.ts" showLineNumbers copy @@ -98,10 +106,15 @@ export const recallTrade = createTool({ }); ``` +**Not sure what tools do?** +Think of them as your agent’s “superpowers”—each tool unlocks new actions for the agent. + --- ## 3. Create the Trading Agent +Let’s build a minimal agent that always buys \$10 of WETH using USDC when prompted. + Create `src/eliza/agents/recall-agent.ts`: ```ts filename="src/eliza/agents/recall-agent.ts" showLineNumbers copy @@ -115,8 +128,8 @@ export const recallAgent = new Agent({ You are a Recall competition trading agent. • Submit exactly one trade when invoked. -• Buy 10 USDC‑worth of WETH regardless of market conditions. -• Use the recall‑trade tool with: +• Buy 10 USDC-worth of WETH regardless of market conditions. +• Use the recall-trade tool with: fromToken = USDC (0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) toToken = WETH (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) amount = "10" @@ -127,10 +140,16 @@ You are a Recall competition trading agent. }); ``` + +Feel free to tweak the instructions—try changing the tokens or amounts and see how the agent behaves! + + --- ## 4. Build the Workflow +Now, let’s wire everything up so your agent can be triggered in one click. + Create `src/eliza/workflows/recall-workflow.ts`: ```ts filename="src/eliza/workflows/recall-workflow.ts" showLineNumbers copy @@ -145,7 +164,7 @@ const tradeStep = createStep({ result: z.string(), }), execute: async ({ mastra }) => { - // "mastra" here refers to the Eliza runtime context + // "mastra" is the Eliza runtime context const agent = mastra?.getAgent('recallAgent'); if (!agent) throw new Error('recallAgent not found'); @@ -174,10 +193,14 @@ recallWorkflow.commit(); export { recallWorkflow }; ``` +**Almost there!** The workflow is the “playbook” your agent will follow when invoked. + --- ## 5. Register Agent and Workflow +Let’s plug your new agent and workflow into the Eliza runtime. + Edit `src/index.ts`: ```ts filename="src/index.ts" showLineNumbers copy @@ -200,6 +223,10 @@ export const eliza = new Eliza({ }); ``` + +You’ve registered your agent and workflow—now for the fun part: trading! + + --- ## 6. Test in the Eliza Dashboard @@ -214,40 +241,58 @@ npm run dev Navigate to: -``` +```copy http://localhost:4111/agents/recallAgent/chat ``` ### 6.3 Place a trade -Type the following message: +Type this in the chat: -``` +```copy Buy $10 worth of Ethereum ``` -The agent processes the request, uses the `recallTrade` tool, and executes a sandbox order on Recall. A confirmation appears in the chat, for example: +Your agent processes the request, calls the `recallTrade` tool, and executes a sandbox order on Recall. +You’ll see a confirmation in the chat, for example: > Trade executed: 0xabc123… (status: filled) + +🎉 Congratulations! Your Eliza bot just traded live on Recall’s sandbox. + + + +If the dashboard doesn’t load or you see errors: +- Make sure your API keys are correct in `.env` +- Check server logs for errors +- Need help? [Join the Recall Discord](#) or check the Eliza docs! + + --- ## 7. Troubleshooting -| Symptom or message | Likely cause | Solution | -| ------------------------- | -------------------- | ----------------------------------- | -| `401 Unauthorized` | Invalid Recall key | Verify `RECALL_API_KEY` in `.env` | -| `429 Too Many Requests` | Rate limit hit | Allow axios‑retry to back‑off | -| “Not enough cash/balance” | Sandbox faucet empty | Request USDC from the Recall faucet | +Hit a snag? Here’s how to get back on track: + +| Symptom or message | Likely cause | Solution | +| ------------------------- | -------------------- | --------------------------------------------------------------------------- | +| `401 Unauthorized` | Invalid Recall key | Verify `RECALL_API_KEY` in `.env` | +| `429 Too Many Requests` | Rate limit hit | Allow axios-retry to back off | +| “Not enough cash/balance” | Sandbox faucet empty | Get USDC from the Recall faucet | + +Still stuck? [Ask for help in the Recall Discord](#) or Eliza community! --- ## 8. Next Steps -* **Enhance prompts** to include dynamic market logic. -* **Add memory** with LibSQL or Redis to track open positions. -* **Deploy** to Fly.io or Docker Swarm for production use. -* **Enter a Recall competition** once your key is sandbox‑verified. +You just built and ran a fully automated Eliza trading agent in minutes—seriously, well done! 🚀 -Your Eliza-powered bot is now live and capable of trading on Recall in under five minutes. +* **Go deeper:** Enhance your prompts with dynamic market logic +* **Track positions:** Add memory with LibSQL or Redis +* **Deploy for real:** Try Fly.io or Docker Swarm for production +* **Compete:** Once sandbox-verified, enter a Recall competition and see how you stack up! +Join the Recall dev community, share your wins, and keep building. +See you—and your bot—on the leaderboard! diff --git a/docs/competitions/guides/vercel.mdx b/docs/competitions/guides/vercel.mdx index 3dbdd85..3bf531f 100644 --- a/docs/competitions/guides/vercel.mdx +++ b/docs/competitions/guides/vercel.mdx @@ -1,3 +1,4 @@ + --- title: Serverless Trader with Next.js 13 & Recall description: Guide to build and deploy a Recall trading bot using Next.js 13, Vercel Functions, and the Vercel AI SDK. @@ -5,32 +6,44 @@ description: Guide to build and deploy a Recall trading bot using Next.js 13, # Introduction -This tutorial demonstrates how to combine **Next.js 13**, **Vercel Functions**, and the **Vercel AI SDK** to create a fully serverless trading bot that submits orders to the Recall Network. You will: +Ready to build and deploy a fully serverless AI trading bot—end to end—in under an hour? 🚀 +This hands-on guide shows how to combine **Next.js 13**, **Vercel Functions**, and the **Vercel AI SDK** to create a bot that streams LLM decisions, executes sandbox trades, and runs globally on Vercel’s edge—no backend servers required. -1. Scaffold a TypeScript Next.js 13 application. -2. Implement an edge function that decides and places trades. -3. Build a lightweight React UI using the AI SDK’s `useChat` hook. -4. Test locally, then deploy with a single `vercel --prod`. +Here’s what you’ll accomplish: +1. Scaffold a Next.js 13 project +2. Implement an edge function for trade decisions and execution +3. Build a React UI with the AI SDK’s `useChat` hook +4. Test locally, then deploy worldwide with a single command -The result is a production‑ready service that streams AI output, executes sandbox trades, and runs entirely on Vercel’s global edge. +No Recall or Vercel experience required—just bring basic Node and TypeScript skills. Let’s dive in! --- ## 1. Prerequisites | Requirement | Minimum version | Purpose | -| ----------------------- | --------------- | ------------------------------------ | -| **Node.js** | 20 + | Local Next.js runtime | -| **npm** | Comes with Node | Package manager | -| **Vercel CLI** | 34 + | Deploy & manage environment vars | -| **OpenAI API key** | – | LLM reasoning via AI SDK | -| **Recall API key & URL**| – | Access to trading endpoints | -| **Vercel account** | – | Hosting & edge functions | +|-------------------------|----------------|--------------------------------------| +| **Node.js** | 20 + | Local Next.js runtime | +| **npm** | Comes with Node| Package manager | +| **Vercel CLI** | 34 + | Deploy & manage environment vars | +| **OpenAI API key** | – | LLM reasoning via AI SDK | +| **Recall API key & URL**| – | Access to trading endpoints | +| **Vercel account** | – | Hosting & edge functions | + + +Need to get set up? +- Install Vercel CLI +- Get your OpenAI API key +- Register for a Recall API key +Don’t forget to add .env.local to .gitignore—keep those secrets safe! + --- ## 2. Project Setup +Let’s spin up your Next.js 13 app with all the right features: + ### 2.1 Create the Next.js app ```bash copy @@ -38,6 +51,8 @@ npx create-next-app@latest recall-vercel-bot --ts --app --eslint --tailwind --sr cd recall-vercel-bot ```` +This sets up TypeScript, app router, ESLint, Tailwind CSS, and puts your code in `src/`. + ### 2.2 Install runtime packages ```bash copy @@ -48,7 +63,7 @@ npm install ai axios axios-retry ## 3. Environment Variables -Add variables locally in `.env.local` (automatically git‑ignored): +Store your keys locally in `.env.local` (already git-ignored): ```dotenv filename=".env.local" copy OPENAI_API_KEY=sk-... @@ -56,18 +71,24 @@ RECALL_API_KEY=rk-... RECALL_API_URL=https://api.sandbox.competitions.recall.network ``` -Set them in Vercel later: +Then, set them in Vercel for deployment: -```bash +```bash copy vercel env add OPENAI_API_KEY vercel env add RECALL_API_KEY vercel env add RECALL_API_URL ``` + +With your environment secured, your bot’s trades and LLM prompts stay private and production-ready. + + --- ## 4. Edge Function: `route.ts` +Now let’s give your bot a brain and a trading hand—with a blazing-fast edge function! + Create `src/app/api/trade/route.ts`: ```ts filename="src/app/api/trade/route.ts" showLineNumbers copy @@ -136,10 +157,16 @@ export async function POST(req: Request) { } ``` + +Edge functions run close to your users for low-latency AI and instant trades—no backend server required! + + --- ## 5. React Front‑End +Let’s give your bot a friendly UI! + Create `src/app/page.tsx`: ```tsx filename="src/app/page.tsx" showLineNumbers copy @@ -196,52 +223,91 @@ export default function Home() { } ``` + +Your UI is live! Try customizing the prompt or styling for your own brand. + + --- ## 6. Local Test +Ready to see your bot in action? +Start the local dev server: + ```bash copy npm run dev ``` -Open `http://localhost:3000`, ask “Should we buy now?”. -If the model responds with `{"execute":true,…}`, the edge function streams the decision and places a sandbox trade—visible in your console and the Recall dashboard. +Open [http://localhost:3000](http://localhost:3000), and ask “Should we buy now?” in the chat box. + +**What to expect:** + +* If the AI decides to execute, you’ll see a streamed response and a trade placed in the Recall sandbox (visible in your server logs and Recall dashboard). + + +Trouble connecting? +- Double-check your environment variables +- Look for errors in your server log +- Still stuck? [Ask for help in the Recall Discord](#) + --- ## 7. Deploy to Vercel +Let’s go global! + ```bash copy vercel --prod ``` -Vercel picks up environment variables, builds the Next.js app, and deploys edge functions globally. The production URL is printed at the end of the deployment. +Vercel picks up your env variables, builds the Next.js app, and deploys edge functions worldwide. +The production URL appears at the end—share it or open it right away! + + +🎉 You just shipped a serverless trading bot to the world! + --- ## 8. Validate in Recall -1. Log in to the Recall dashboard. -2. Confirm the sandbox order appears in **Orders → Sandbox**. -3. Your API key is now whitelisted for live competitions. +1. Log in to your [Recall dashboard](https://recall.network). +2. Go to **Orders → Sandbox** to confirm your bot’s trade shows up. +3. Your API key is now whitelisted for live competitions—welcome to Recall! + + +Once you’re whitelisted, you can join live competitions and start climbing the leaderboard. See you there! + --- ## 9. Troubleshooting -| Message / symptom | Likely cause | Resolution | -| --------------------------- | -------------------------- | ----------------------------------------------- | -| `401 Unauthorized` | Invalid Recall key | Regenerate key and re‑add in Vercel dashboard | -| `429 Too Many Requests` | Recall rate limit | Axios‑retry handles back‑off automatically | -| Edge function build error | Unsupported Node API | Keep only Web API–compatible code in `route.ts` | -| “Missing env var” at deploy | Variable not set in Vercel | `vercel env add ` before deploy | +Hit a snag? You’re not alone—here are common fixes: + +| Message / symptom | Likely cause | Resolution | +| --------------------------- | -------------------------- | ---------------------------------------------- | +| `401 Unauthorized` | Invalid Recall key | Regenerate key and re‑add in Vercel dashboard | +| `429 Too Many Requests` | Recall rate limit | Axios‑retry handles back‑off automatically | +| Edge function build error | Unsupported Node API | Only use Web API–compatible code in `route.ts` | +| “Missing env var” at deploy | Variable not set in Vercel | `vercel env add ` before deploy | + +Still need help? + +* [Join the Recall Discord](#) or ask in the Vercel community +* Share your code or error logs—someone’s always happy to help! --- -## 10. Scalability Notes +## 10. Scalability & Next Steps + +* **Vercel Cron:** Schedule `/api/trade` POSTs nightly for automated backtests or daily rebalancing. +* **Edge Middleware:** Add JWT or session validation for endpoint security. +* **Observability:** Pipe AI latency and trade metrics to Vercel Analytics for monitoring. -* **Vercel Cron**: schedule `/api/trade` POSTs nightly for back‑tests. -* **Edge Middleware**: add JWT validation to protect the endpoint. -* **Observability**: forward AI latency and trade metrics to Vercel Analytics. +**You did it!** +You’ve built, shipped, and validated a serverless AI trading bot—fully powered by Next.js 13, Vercel Functions, the AI SDK, and Recall. +Join the Recall community, share your build, and take your bot to the leaderboard! -Your serverless trading bot is live—powered by Next.js 13, Vercel Functions, and the AI SDK, with all orders routed securely through Recall’s sandbox environment. +Happy hacking! 🚀 From b97214aa16a811e12d8eda9265d73d0666a6e806 Mon Sep 17 00:00:00 2001 From: Mikers Date: Fri, 18 Jul 2025 10:16:08 -1000 Subject: [PATCH 3/9] fix bugs --- docs/competitions/guides/eliza.mdx | 4 ++-- docs/competitions/guides/vercel.mdx | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index a8d89c1..cc6f9e2 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -241,7 +241,7 @@ npm run dev Navigate to: -```copy +```md copy http://localhost:4111/agents/recallAgent/chat ``` @@ -249,7 +249,7 @@ http://localhost:4111/agents/recallAgent/chat Type this in the chat: -```copy +```md copy Buy $10 worth of Ethereum ``` diff --git a/docs/competitions/guides/vercel.mdx b/docs/competitions/guides/vercel.mdx index 3bf531f..17e5eee 100644 --- a/docs/competitions/guides/vercel.mdx +++ b/docs/competitions/guides/vercel.mdx @@ -1,6 +1,5 @@ - --- -title: Serverless Trader with Next.js 13 & Recall +title: Serverless Trader with Next.js 13 and Recall description: Guide to build and deploy a Recall trading bot using Next.js 13, Vercel Functions, and the Vercel AI SDK. --- From 3ddae549433cc9e457171013df01e439ae8bb38e Mon Sep 17 00:00:00 2001 From: Mikers Date: Fri, 18 Jul 2025 12:01:09 -1000 Subject: [PATCH 4/9] new --- docs/competitions/guides/eliza2.mdx | 223 ++++++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 docs/competitions/guides/eliza2.mdx diff --git a/docs/competitions/guides/eliza2.mdx b/docs/competitions/guides/eliza2.mdx new file mode 100644 index 0000000..8a525e0 --- /dev/null +++ b/docs/competitions/guides/eliza2.mdx @@ -0,0 +1,223 @@ +--- +title: Five Minute Eliza Trader +description: Build and run a Recall-trading AI agent with **pure Eliza features**—no Mastra, no hacks. +--- + + +## 0 · Overview 🎯 + +You’ll spin up an Eliza agent that can: + +1. **Decide** whether to buy WETH with USDC. +2. **Execute** the trade on Recall’s sandbox via a custom **plugin action**. +3. **Chat** in real time through Eliza’s built-in web UI. + +All in ≈ 5 minutes. + +--- + +## 1 · Prerequisites 🔧 + +| Requirement | Version / Notes | +|----------------------------|----------------------------------| +| **Node.js** | 20 + | +| **bun** | 1.1 + (Eliza CLI is a Bun app) | +| **OpenAI API key** | For LLM reasoning | +| **Recall API key & URL** | `https://api.sandbox.competitions.recall.network` | +| **Git** + **Terminal** | Any platform (macOS / Linux / WSL) | + + +Need keys? +• OpenAI dashboard +• Recall registration + + +--- + +## 2 · Install the CLI & Create a Project + +```bash copy +bun i -g @elizaos/cli # ⚡ one-time install +elizaos create recall-eliza-bot +cd recall-eliza-bot +bun install # installs deps for the new project +```` + +The generator scaffolds: + +``` +eliza.config.ts # global agent config +character.ts # personality & instructions +plugins/ # place for first-party & custom plugins +``` + +--- + +## 3 · Add Environment Secrets + +Create `.env` at the project root: + +```dotenv filename=".env" copy +OPENAI_API_KEY=sk-... +RECALL_API_KEY=rk-... +RECALL_API_URL=https://api.sandbox.competitions.recall.network +``` + +*ElizaOS autoloads `.env` during `elizaos start`.* + +--- + +## 4 · Write a **Recall Trade** Plugin + +Plugins live inside `plugins/*`. +Create `plugins/plugin-recall-trade/src/index.ts`: + +```ts filename="plugins/plugin-recall-trade/src/index.ts" showLineNumbers copy +import { definePlugin } from "@elizaos/core"; +import { z } from "zod"; +import axios from "axios"; + +export default definePlugin(({ env }) => ({ + actions: { + "recall.trade": { + description: "Swap USDC → WETH on Recall sandbox", + input: z.object({ + fromToken: z.string(), + toToken: z.string(), + amount: z.string(), + reason: z.string().optional(), + }), + output: z.object({ + txHash: z.string(), + status: z.string(), + }), + handler: async ({ input }) => { + const res = await axios.post( + `${env.RECALL_API_URL}/api/trade/execute`, + input, + { headers: { Authorization: `Bearer ${env.RECALL_API_KEY}` }, + timeout: 30_000 } + ); + return { txHash: res.data.txHash, status: res.data.status }; + }, + }, + }, +})); +``` + +> **Why `definePlugin`?** +> In Eliza, *everything*—clients, memory stores, actions—is a plugin. +> Actions are invoked by name inside your agent’s prompt or via APIs. + +--- + +## 5 · Register the Plugin & LLM + +Edit `eliza.config.ts`: + +```ts filename="eliza.config.ts" showLineNumbers copy +import recallTradePlugin from "./plugins/plugin-recall-trade"; +import { openaiProvider } from "@elizaos/provider-openai"; +import { bootstrapPlugin } from "@elizaos/plugin-bootstrap"; + +export default { + character: "./character.ts", + providers: [ + openaiProvider({ + model: "gpt-4o-mini", // fast + cheap + }), + ], + plugins: [ + bootstrapPlugin(), // built-in logging, web UI, etc. + recallTradePlugin(), // ← our custom action + ], +}; +``` + +--- + +## 6 · Define the Agent’s Instructions + +Open `character.ts`: + +```ts filename="character.ts" showLineNumbers copy +export default { + name: "Recall Trader", + persona: "A pragmatic crypto-trading bot for competitions.", + instructions: ` +When the user says anything like "trade" or "buy", decide +whether to buy WETH with 10 USDC. If yes, call the +\`recall.trade\` action exactly once with: + +fromToken = "0xA0b8...eB48" # USDC +toToken = "0xC02a...6Cc2" # WETH +amount = "10" +reason = "tutorial trade" + +Respond with the JSON you receive from the action. +`, + examples: [ + ["User", "Can you place a test trade?"], + ["Assistant", "Sure → executing trade... ✅"], + ], +}; +``` + +--- + +## 7 · Run the Agent Locally + +```bash copy +elizaos start +``` + +The **bootstrap plugin** spins up a local web UI (default `http://localhost:3111`). + +*Chat prompt:* + +``` +Place a tutorial trade please +``` + +**Success indicators** + +1. Chat response shows a JSON object `{ "txHash": "...", "status": "filled" }`. +2. Terminal logs display `Recall trade txHash: 0xabc123...`. +3. Recall dashboard → **Orders → Sandbox** shows the new order. + + +🎉 Congrats—your Eliza agent just traded on Recall! + + +--- + +## 8 · Deploy (Optional) + +Eliza projects are plain Node apps—deploy via Docker, Fly.io, or Vercel Functions. +Example Dockerfile is shipped (`Dockerfile`)—just set the same env vars in your cloud. + +--- + +## 9 · Troubleshooting + +| Symptom / log | Likely cause | Fix | +| -------------------------------------- | ----------------------- | --------------------------------------- | +| `RecallError: 401 Unauthorized` | Wrong `RECALL_API_KEY` | Regenerate key → update `.env` | +| `OpenAIAuthenticationError` | Invalid OpenAI key | Verify `.env` entry | +| `ZodError: input validation failed` | Agent passed bad params | Check amounts / token addresses | +| Action name not found (`recall.trade`) | Plugin not loaded | Ensure plugin path & `.ts` compiled | +| Nothing happens on `/start` | Port conflict | Set `PORT=3112` in `.env` or Dockerfile | + +Need more help? Join the **#eliza** channel in the Recall Discord or the +[ElizaOS Discord](https://discord.gg/elizaos). + +--- + +## 10 · Next Steps 🚀 + +* **Dynamic sizing**: Read market price via a Web-search or DEX plugin and size trades. +* **Memory**: Add `@elizaos/plugin-memory-redis` to track PnL over time. +* **Scheduled runs**: Pair with GitHub Actions or a cron wrapper to auto-trade nightly. +* **Competitions**: With the sandbox trade complete, your key is whitelisted—join your first Recall event and climb the leaderboard! + +Happy hacking, and see you (and your Eliza bot) on the charts! 🚀 From 667adfd833528d5cbb4c84c561da8240b3b85235 Mon Sep 17 00:00:00 2001 From: Mikers Date: Mon, 21 Jul 2025 01:08:11 -1000 Subject: [PATCH 5/9] install info --- docs/competitions/guides/eliza.mdx | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index cc6f9e2..cfe1230 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -12,7 +12,7 @@ By the end, you’ll have placed a real (test) trade, seen your agent in action, 4. Register a workflow 5. Place your first order through the Eliza dashboard -This guide is perfect for TypeScript developers comfy with Node 20+ but new to Eliza or Recall. If that’s you—let’s dive in! +This guide is perfect for TypeScript developers comfortable with Node 20+ but new to Eliza or Recall. If that’s you—let’s dive in! --- @@ -39,11 +39,24 @@ Store all keys in a .env file at the project root—keep them out o Ready? Let’s spin up your workspace: ```bash copy -npm create eliza@latest recall-eliza-bot +npm i -g @elizaos/cli +elizaos create recall-eliza-bot cd recall-eliza-bot ```` -When prompted, choose the **blank** template. + + During the setup process, you'll be prompted to make the following selections: + + 1. **Database**: Select `pglite` for a lightweight PostgreSQL option + 2. **Model Provider**: Select `openai` + 3. **API Key**: Provide your OpenAI API key when prompted + + + Make sure you have your OpenAI API key ready. You can get one from the [OpenAI Platform](https://platform.openai.com/). + + + + **Next, install a couple of helpers:** @@ -54,8 +67,7 @@ npm install axios axios-retry Now set up your secrets: ```dotenv filename=".env" copy -OPENAI_API_KEY=sk-... -RECALL_API_KEY=rk-... +RECALL_API_KEY=... RECALL_API_URL=https://api.sandbox.competitions.recall.network ``` From 7f63c51519e4b7bad36b02e766b58c912cd1510a Mon Sep 17 00:00:00 2001 From: nijoe1 Date: Mon, 21 Jul 2025 21:45:11 +0300 Subject: [PATCH 6/9] feat: major eliza guide improvement/testing --- docs/competitions/guides/eliza.mdx | 548 ++++++++++++++++------------ docs/competitions/guides/eliza2.mdx | 223 ----------- docs/competitions/guides/meta.json | 12 +- 3 files changed, 317 insertions(+), 466 deletions(-) delete mode 100644 docs/competitions/guides/eliza2.mdx diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index cfe1230..bd8bc2b 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -1,310 +1,376 @@ --- -title: Five‑Minute Eliza Trader -description: Rapid guide to scaffold an Eliza agent and execute a sandbox trade on the Recall Network. +title: Five Minute Eliza Trader +description: Build and run a Recall-trading AI agent with ElizaOS. --- -Welcome! Let’s go from zero to your first Eliza-powered trading bot on Recall—in under five minutes. 🚀 -By the end, you’ll have placed a real (test) trade, seen your agent in action, and unlocked the door to deeper automation. Here’s the roadmap: -1. Scaffold a new Eliza project -2. Add a Recall trade tool -3. Create a minimal trading agent -4. Register a workflow -5. Place your first order through the Eliza dashboard +## Overview -This guide is perfect for TypeScript developers comfortable with Node 20+ but new to Eliza or Recall. If that’s you—let’s dive in! +You’ll spin up an Eliza agent that can: + +1. **Execute** a trade on Recall’s sandbox via a custom **plugin action**. +2. **Chat** in real time through Eliza’s built-in web UI. +3. **Learn** how to improve your Eliza powered agent. + +All in ≈ 5 minutes. --- ## Prerequisites -| Requirement | Minimum version | Purpose | -|------------------------|----------------|--------------------------------------| -| **Node.js** | 20+ | Runtime for the bot | -| **npm** | Comes with Node| Package manager | -| **OpenAI API key** | – | LLM reasoning for the Eliza agent | -| **Recall API key & URL**| – | Access to trading endpoints | +| Requirement | Version / Notes | +|----------------------------|----------------------------------| +| **Node.js** | 20 + | +| **bun** | 1.1 + (Eliza CLI is a Bun app) | +| **OpenAI API key** | For LLM reasoning | +| **Recall API key & URL** | `https://api.sandbox.competitions.recall.network` | +| **Git** + **Terminal** | Any platform (macOS / Linux / WSL) | -Don’t have your keys yet? -- Get an OpenAI API key -- Register for a Recall API key -Store all keys in a .env file at the project root—keep them out of source control! +Need keys? +• OpenAI dashboard +• Recall registration ---- +## Step by step guide -## 1. Scaffold the Project + -Ready? Let’s spin up your workspace: + + +### Install the eliza CLI & create a project ```bash copy -npm i -g @elizaos/cli +bun i -g @elizaos/cli # ⚡ one-time install elizaos create recall-eliza-bot cd recall-eliza-bot -```` - - - During the setup process, you'll be prompted to make the following selections: - - 1. **Database**: Select `pglite` for a lightweight PostgreSQL option - 2. **Model Provider**: Select `openai` - 3. **API Key**: Provide your OpenAI API key when prompted - - - Make sure you have your OpenAI API key ready. You can get one from the [OpenAI Platform](https://platform.openai.com/). - - +bun install # installs deps for the new project +``` +The generator scaffolds: +``` +eliza.config.ts # global agent config +character.ts # personality & instructions +plugins/ # place for first-party & custom plugins +``` -**Next, install a couple of helpers:** + -```bash copy -npm install axios axios-retry -``` + +### Set up your environment variables -Now set up your secrets: +Create `.env` at the project root: ```dotenv filename=".env" copy -RECALL_API_KEY=... +OPENAI_API_KEY=sk-... +RECALL_API_KEY=rk-... RECALL_API_URL=https://api.sandbox.competitions.recall.network ``` - -Your `.env` file keeps credentials safe and separate from your code. Pro tip: Always add `.env` to `.gitignore`! - - ---- +*ElizaOS autoloads `.env` during `elizaos start`.* + + + + +### Write a Recall trade plugin + +Plugins live inside `plugins/*`. +Create `plugins/plugin-recall-trade.ts`: + +```ts filename="plugins/plugin-recall-trade.ts" showLineNumbers copy +import type { + Plugin, + Action, + ActionResult, + HandlerCallback, + IAgentRuntime, + Memory, + State, +} from "@elizaos/core"; +import { z } from "zod"; +import { logger } from "@elizaos/core"; +import axios from "axios"; + +const configSchema = z.object({ + RECALL_API_URL: z.string().min(1, "RECALL_API_URL is required"), + RECALL_API_KEY: z.string().min(1, "RECALL_API_KEY is required"), +}); -## 2. Add the Recall Trade Tool - -Time to teach your bot how to trade! In Eliza, “tools” are modular skills an agent can use. - -Create `src/eliza/tools/recall-trade.ts`: - -```ts filename="src/eliza/tools/recall-trade.ts" showLineNumbers copy -import { createTool } from '@eliza/core/tools'; -import axios from 'axios'; -import { z } from 'zod'; - -export const recallTrade = createTool({ - id: 'recall-trade', - description: 'Execute a spot trade on the Recall Network', - inputSchema: z.object({ - fromToken: z.string().describe('ERC‑20 address'), - toToken: z.string().describe('ERC‑20 address'), - amount: z.string().describe('Human‑readable amount in FROM token'), - reason: z.string().optional(), - }), - outputSchema: z.object({ - txHash: z.string(), - status: z.string(), - }), - execute: async ({ fromToken, toToken, amount, reason }) => { - const { RECALL_API_URL, RECALL_API_KEY } = process.env; - - const { data } = await axios.post( - `${RECALL_API_URL}/api/trade/execute`, - { fromToken, toToken, amount, reason }, +const tradeAction: Action = { + name: "RECALL_TRADE", + similes: ["SWAP", "TRADE", "EXCHANGE"], + description: "Swap tokens on Recall sandbox", + validate: async (_runtime: IAgentRuntime, _message: Memory, _state: State) => + true, + handler: async ( + _runtime: IAgentRuntime, + message: Memory, + _state: State, + _options: any, + callback: HandlerCallback, + _responses: Memory[] + ): Promise => { + try { + const env = process.env; + + let input: any = undefined; + + // 1. Try to extract from message.content.input or message.content + if (message.content && typeof message.content === "object") { + } + + // 2. Try to extract from natural language using a model + if (!input && message.content?.text) { + } + + // 3. Fallback to demo trade if nothing else found + if (!input) { + input = { + fromToken: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", + toToken: "So11111111111111111111111111111111111111112", + amount: "10", + reason: + "Strong upward momentum in the market combined with positive news on this token's ecosystem growth.", + slippageTolerance: "0.5", + fromChain: "svm", + fromSpecificChain: "mainnet", + toChain: "svm", + toSpecificChain: "mainnet", + }; + logger.info("Falling back to demo trade input."); + } + + // Send the trade to recall api + const http = axios.create({ + headers: { + Authorization: `Bearer ${process.env.RECALL_API_KEY!}`, + "Content-Type": "application/json", + }, + }); + const res = await http.post( + `${env.RECALL_API_URL}/api/trade/execute`, + JSON.stringify(input) + ); + const result = res.data.transaction; + + console.log("result", result); + + await callback({ + text: `Your trade was executed successfully you bought with ${result.fromAmount} ${result.fromTokenSymbol} ${result.toAmount} ${result.toTokenSymbol}`, + }); + + return { + text: "Trade executed successfully", + values: result, + data: result, + success: true, + }; + } catch (error) { + logger.error("Error in RECALL_TRADE action:", error); + return { + text: "Failed to execute trade", + values: {}, + data: {}, + success: false, + }; + } + }, + examples: [ + [ { - headers: { Authorization: `Bearer ${RECALL_API_KEY}` }, - timeout: 30_000, + name: "User", + content: { + text: "Trade for me", + }, }, - ); - - return { txHash: data.txHash, status: data.status }; + { + name: "Bot", + content: { + text: "I will execute now the demo trade", + actions: ["RECALL_TRADE"], + }, + }, + ], + ], +}; + +const tradePlugin: Plugin = { + name: "tradeplugin", + description: "A plugin to trade tokens on Recall sandbox", + priority: 0, + config: { + RECALL_API_URL: process.env.RECALL_API_URL, + RECALL_API_KEY: process.env.RECALL_API_KEY, }, -}); -``` - -**Not sure what tools do?** -Think of them as your agent’s “superpowers”—each tool unlocks new actions for the agent. - ---- - -## 3. Create the Trading Agent - -Let’s build a minimal agent that always buys \$10 of WETH using USDC when prompted. - -Create `src/eliza/agents/recall-agent.ts`: - -```ts filename="src/eliza/agents/recall-agent.ts" showLineNumbers copy -import { openai } from '@ai-sdk/openai'; -import { Agent } from '@eliza/core/agent'; -import { recallTrade } from '../tools/recall-trade'; - -export const recallAgent = new Agent({ - name: 'Recall Agent', - instructions: ` -You are a Recall competition trading agent. - -• Submit exactly one trade when invoked. -• Buy 10 USDC-worth of WETH regardless of market conditions. -• Use the recall-trade tool with: - fromToken = USDC (0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) - toToken = WETH (0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) - amount = "10" -• Add a short reason like "tutorial trade". -`, - model: openai('gpt-4o-mini'), - tools: { recallTrade }, -}); -``` - - -Feel free to tweak the instructions—try changing the tokens or amounts and see how the agent behaves! - - ---- - -## 4. Build the Workflow - -Now, let’s wire everything up so your agent can be triggered in one click. - -Create `src/eliza/workflows/recall-workflow.ts`: - -```ts filename="src/eliza/workflows/recall-workflow.ts" showLineNumbers copy -import { createStep, createWorkflow } from '@eliza/core/workflows'; -import { z } from 'zod'; - -const tradeStep = createStep({ - id: 'run-recall-agent', - description: 'Invoke the Recall agent once', - inputSchema: z.void(), - outputSchema: z.object({ - result: z.string(), - }), - execute: async ({ mastra }) => { - // "mastra" is the Eliza runtime context - const agent = mastra?.getAgent('recallAgent'); - if (!agent) throw new Error('recallAgent not found'); - - const response = await agent.stream([ - { role: 'user', content: 'Make a trade now.' }, - ]); - - let text = ''; - for await (const chunk of response.textStream) { - text += chunk; + async init(config: Record) { + logger.info("*** Initializing tradeplugin ***"); + try { + const validatedConfig = await configSchema.parseAsync(config); + for (const [key, value] of Object.entries(validatedConfig)) { + if (value) process.env[key] = value; + } + } catch (error) { + throw error; } - - return { result: text }; }, -}); - -const recallWorkflow = createWorkflow({ - id: 'recall-workflow', - outputSchema: z.object({ - result: z.string(), - }), -}).then(tradeStep); - -recallWorkflow.commit(); - -export { recallWorkflow }; + actions: [tradeAction], + models: {}, + routes: [], + events: {}, + services: [], + providers: [], +}; + +export default tradePlugin; ``` -**Almost there!** The workflow is the “playbook” your agent will follow when invoked. - ---- +> **Why `you have to create a plugin`?** +> In Eliza, *everything*—clients, memory stores, actions—is a plugin. +> Actions are invoked by name inside your agent’s prompt or via APIs. -## 5. Register Agent and Workflow + -Let’s plug your new agent and workflow into the Eliza runtime. + +### Register the plugin into your agent -Edit `src/index.ts`: +Edit `./src/index.ts`: ```ts filename="src/index.ts" showLineNumbers copy -import { Eliza } from '@eliza/core/eliza'; -import { PinoLogger } from '@eliza/loggers'; -import { LibSQLStore } from '@eliza/libsql'; -import { recallWorkflow } from './eliza/workflows/recall-workflow'; -import { recallAgent } from './eliza/agents/recall-agent'; - -export const eliza = new Eliza({ - workflows: { recallWorkflow }, - agents: { recallAgent }, - storage: new LibSQLStore({ - url: ':memory:', - }), - logger: new PinoLogger({ - name: 'Eliza', - level: 'info', - }), -}); -``` +import { + logger, + type IAgentRuntime, + type Project, + type ProjectAgent, +} from "@elizaos/core"; +import { character } from "./character.ts"; +import tradePlugin from "./plugins/plugin-recall-trade.ts"; + +const initCharacter = ({ runtime }: { runtime: IAgentRuntime }) => { + logger.info("Initializing character"); + logger.info("Name: ", character.name); +}; + +export const projectAgent: ProjectAgent = { + character, + init: async (runtime: IAgentRuntime) => await initCharacter({ runtime }), + plugins: [tradePlugin], +}; +const project: Project = { + agents: [projectAgent], +}; + +// Export test suites for the test runner +export { testSuites } from "./__tests__/e2e"; +export { character } from "./character.ts"; + +export default project; - -You’ve registered your agent and workflow—now for the fun part: trading! - +``` + + + +### Define your agent's character + +Open `./src/character.ts`: + +```ts filename="src/character.ts" showLineNumbers copy +import { type Character } from "@elizaos/core"; +/** + * Represents the default character Recall Trader. + * Recall Trader can be extended to become the best trading agent in the trading competitions that are held on the Recall platform. + * Extend him to impove his trading strategies and improve his performance in the trading competitions. + */ +export const character: Character = { + name: "Recall Trader", + plugins: [ + // Core plugins first + "@elizaos/plugin-sql", + // Embedding-capable plugins (optional, based on available credentials) + ...(process.env.OPENAI_API_KEY?.trim() ? ["@elizaos/plugin-openai"] : []), + // Bootstrap plugin + ...(!process.env.IGNORE_BOOTSTRAP ? ["@elizaos/plugin-bootstrap"] : []), + ], + settings: { + model: "gpt-4o-mini", + secrets: {}, + avatar: "https://elizaos.github.io/eliza-avatars/Eliza/portrait.png", + }, + system: + "You are a pro trader and you help users trade on the blockchain using the Recall API demo trade plugin.", + bio: [ + "Pro trader", + "Helps users trade on the blockchain using the Recall API demo plugin", + "Offers assistance proactively", + "Communicates clearly and directly", + ], + topics: ["trading", "blockchain", "crypto"], + style: { + all: [ + "Be engaging and conversational", + "Care more about trading than other topics", + "Respond to all types of questions but mostly to questions about trading and trading strategies", + ], + chat: [ + "Be conversational and natural", + "Engage with trading topics", + "Be helpful and informative", + ], + }, +}; ---- +``` -## 6. Test in the Eliza Dashboard + -### 6.1 Start the server + +### Run the agent locally ```bash copy -npm run dev +elizaos start ``` -### 6.2 Open the dashboard +The **bootstrap plugin** spins up a local web UI (default `http://localhost:3111`). -Navigate to: +*Chat prompt:* -```md copy -http://localhost:4111/agents/recallAgent/chat ``` - -### 6.3 Place a trade - -Type this in the chat: - -```md copy -Buy $10 worth of Ethereum +Place a tutorial trade please ``` -Your agent processes the request, calls the `recallTrade` tool, and executes a sandbox order on Recall. -You’ll see a confirmation in the chat, for example: +**Success indicators** -> Trade executed: 0xabc123… (status: filled) +1. Chat response shows `Your trade was executed successfully you bought with 10 USDC 0.051 SOL`. +2. Terminal logs display `The successful response from the Recall API`. +3. Recall dashboard → **Orders → Sandbox** shows the new order. -🎉 Congratulations! Your Eliza bot just traded live on Recall’s sandbox. +🎉 Congrats—your Eliza agent just traded on Recall! - -If the dashboard doesn’t load or you see errors: -- Make sure your API keys are correct in `.env` -- Check server logs for errors -- Need help? [Join the Recall Discord](#) or check the Eliza docs! - + ---- - -## 7. Troubleshooting + -Hit a snag? Here’s how to get back on track: +## Troubleshooting -| Symptom or message | Likely cause | Solution | -| ------------------------- | -------------------- | --------------------------------------------------------------------------- | -| `401 Unauthorized` | Invalid Recall key | Verify `RECALL_API_KEY` in `.env` | -| `429 Too Many Requests` | Rate limit hit | Allow axios-retry to back off | -| “Not enough cash/balance” | Sandbox faucet empty | Get USDC from the Recall faucet | +| Symptom / log | Likely cause | Fix | +| -------------------------------------- | ----------------------- | --------------------------------------- | +| `RecallError: 401 Unauthorized` | Wrong `RECALL_API_KEY` | Regenerate key → update `.env` | +| `OpenAIAuthenticationError` | Invalid OpenAI key | Verify `.env` entry | +| `ZodError: input validation failed` | Agent passed bad params | Check amounts / token addresses | +| Action name not found (`recall.trade`) | Plugin not loaded | Ensure plugin path & `.ts` compiled | +| Nothing happens on `/start` | Port conflict | Set `PORT=3112` in `.env` or Dockerfile | -Still stuck? [Ask for help in the Recall Discord](#) or Eliza community! - ---- +Need more help? Join the **#eliza** channel in the Recall Discord or the +[ElizaOS Discord](https://discord.gg/elizaos). -## 8. Next Steps -You just built and ran a fully automated Eliza trading agent in minutes—seriously, well done! 🚀 +## Next Steps -* **Go deeper:** Enhance your prompts with dynamic market logic -* **Track positions:** Add memory with LibSQL or Redis -* **Deploy for real:** Try Fly.io or Docker Swarm for production -* **Compete:** Once sandbox-verified, enter a Recall competition and see how you stack up! +* **Dynamic sizing**: Read market price via a Web-search or DEX plugin and size trades. +* **Memory**: Add `@elizaos/plugin-memory-redis` to track PnL over time. +* **Scheduled runs**: Pair with GitHub Actions or a cron wrapper to auto-trade nightly. +* **Competitions**: With the sandbox trade complete, your key is whitelisted—join your first Recall event and climb the leaderboard! -Join the Recall dev community, share your wins, and keep building. -See you—and your bot—on the leaderboard! +Happy hacking, and see you (and your Eliza bot) on the charts! 🚀 diff --git a/docs/competitions/guides/eliza2.mdx b/docs/competitions/guides/eliza2.mdx deleted file mode 100644 index 8a525e0..0000000 --- a/docs/competitions/guides/eliza2.mdx +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Five Minute Eliza Trader -description: Build and run a Recall-trading AI agent with **pure Eliza features**—no Mastra, no hacks. ---- - - -## 0 · Overview 🎯 - -You’ll spin up an Eliza agent that can: - -1. **Decide** whether to buy WETH with USDC. -2. **Execute** the trade on Recall’s sandbox via a custom **plugin action**. -3. **Chat** in real time through Eliza’s built-in web UI. - -All in ≈ 5 minutes. - ---- - -## 1 · Prerequisites 🔧 - -| Requirement | Version / Notes | -|----------------------------|----------------------------------| -| **Node.js** | 20 + | -| **bun** | 1.1 + (Eliza CLI is a Bun app) | -| **OpenAI API key** | For LLM reasoning | -| **Recall API key & URL** | `https://api.sandbox.competitions.recall.network` | -| **Git** + **Terminal** | Any platform (macOS / Linux / WSL) | - - -Need keys? -• OpenAI dashboard -• Recall registration - - ---- - -## 2 · Install the CLI & Create a Project - -```bash copy -bun i -g @elizaos/cli # ⚡ one-time install -elizaos create recall-eliza-bot -cd recall-eliza-bot -bun install # installs deps for the new project -```` - -The generator scaffolds: - -``` -eliza.config.ts # global agent config -character.ts # personality & instructions -plugins/ # place for first-party & custom plugins -``` - ---- - -## 3 · Add Environment Secrets - -Create `.env` at the project root: - -```dotenv filename=".env" copy -OPENAI_API_KEY=sk-... -RECALL_API_KEY=rk-... -RECALL_API_URL=https://api.sandbox.competitions.recall.network -``` - -*ElizaOS autoloads `.env` during `elizaos start`.* - ---- - -## 4 · Write a **Recall Trade** Plugin - -Plugins live inside `plugins/*`. -Create `plugins/plugin-recall-trade/src/index.ts`: - -```ts filename="plugins/plugin-recall-trade/src/index.ts" showLineNumbers copy -import { definePlugin } from "@elizaos/core"; -import { z } from "zod"; -import axios from "axios"; - -export default definePlugin(({ env }) => ({ - actions: { - "recall.trade": { - description: "Swap USDC → WETH on Recall sandbox", - input: z.object({ - fromToken: z.string(), - toToken: z.string(), - amount: z.string(), - reason: z.string().optional(), - }), - output: z.object({ - txHash: z.string(), - status: z.string(), - }), - handler: async ({ input }) => { - const res = await axios.post( - `${env.RECALL_API_URL}/api/trade/execute`, - input, - { headers: { Authorization: `Bearer ${env.RECALL_API_KEY}` }, - timeout: 30_000 } - ); - return { txHash: res.data.txHash, status: res.data.status }; - }, - }, - }, -})); -``` - -> **Why `definePlugin`?** -> In Eliza, *everything*—clients, memory stores, actions—is a plugin. -> Actions are invoked by name inside your agent’s prompt or via APIs. - ---- - -## 5 · Register the Plugin & LLM - -Edit `eliza.config.ts`: - -```ts filename="eliza.config.ts" showLineNumbers copy -import recallTradePlugin from "./plugins/plugin-recall-trade"; -import { openaiProvider } from "@elizaos/provider-openai"; -import { bootstrapPlugin } from "@elizaos/plugin-bootstrap"; - -export default { - character: "./character.ts", - providers: [ - openaiProvider({ - model: "gpt-4o-mini", // fast + cheap - }), - ], - plugins: [ - bootstrapPlugin(), // built-in logging, web UI, etc. - recallTradePlugin(), // ← our custom action - ], -}; -``` - ---- - -## 6 · Define the Agent’s Instructions - -Open `character.ts`: - -```ts filename="character.ts" showLineNumbers copy -export default { - name: "Recall Trader", - persona: "A pragmatic crypto-trading bot for competitions.", - instructions: ` -When the user says anything like "trade" or "buy", decide -whether to buy WETH with 10 USDC. If yes, call the -\`recall.trade\` action exactly once with: - -fromToken = "0xA0b8...eB48" # USDC -toToken = "0xC02a...6Cc2" # WETH -amount = "10" -reason = "tutorial trade" - -Respond with the JSON you receive from the action. -`, - examples: [ - ["User", "Can you place a test trade?"], - ["Assistant", "Sure → executing trade... ✅"], - ], -}; -``` - ---- - -## 7 · Run the Agent Locally - -```bash copy -elizaos start -``` - -The **bootstrap plugin** spins up a local web UI (default `http://localhost:3111`). - -*Chat prompt:* - -``` -Place a tutorial trade please -``` - -**Success indicators** - -1. Chat response shows a JSON object `{ "txHash": "...", "status": "filled" }`. -2. Terminal logs display `Recall trade txHash: 0xabc123...`. -3. Recall dashboard → **Orders → Sandbox** shows the new order. - - -🎉 Congrats—your Eliza agent just traded on Recall! - - ---- - -## 8 · Deploy (Optional) - -Eliza projects are plain Node apps—deploy via Docker, Fly.io, or Vercel Functions. -Example Dockerfile is shipped (`Dockerfile`)—just set the same env vars in your cloud. - ---- - -## 9 · Troubleshooting - -| Symptom / log | Likely cause | Fix | -| -------------------------------------- | ----------------------- | --------------------------------------- | -| `RecallError: 401 Unauthorized` | Wrong `RECALL_API_KEY` | Regenerate key → update `.env` | -| `OpenAIAuthenticationError` | Invalid OpenAI key | Verify `.env` entry | -| `ZodError: input validation failed` | Agent passed bad params | Check amounts / token addresses | -| Action name not found (`recall.trade`) | Plugin not loaded | Ensure plugin path & `.ts` compiled | -| Nothing happens on `/start` | Port conflict | Set `PORT=3112` in `.env` or Dockerfile | - -Need more help? Join the **#eliza** channel in the Recall Discord or the -[ElizaOS Discord](https://discord.gg/elizaos). - ---- - -## 10 · Next Steps 🚀 - -* **Dynamic sizing**: Read market price via a Web-search or DEX plugin and size trades. -* **Memory**: Add `@elizaos/plugin-memory-redis` to track PnL over time. -* **Scheduled runs**: Pair with GitHub Actions or a cron wrapper to auto-trade nightly. -* **Competitions**: With the sandbox trade complete, your key is whitelisted—join your first Recall event and climb the leaderboard! - -Happy hacking, and see you (and your Eliza bot) on the charts! 🚀 diff --git a/docs/competitions/guides/meta.json b/docs/competitions/guides/meta.json index 64f7fd8..07e0b8f 100644 --- a/docs/competitions/guides/meta.json +++ b/docs/competitions/guides/meta.json @@ -1,5 +1,13 @@ { "title": "Join competitions", - "pages": ["register", "setup", "mcp", "trading", "eliza", - "vercel","portfolio-manager-tutorial", "faq"] + "pages": [ + "register", + "setup", + "mcp", + "trading", + "eliza", + "vercel", + "portfolio-manager-tutorial", + "faq" + ] } From 08e3aa81b07d54d2c880c31209e448bc2c8439ef Mon Sep 17 00:00:00 2001 From: nijoe1 Date: Tue, 22 Jul 2025 16:24:28 +0300 Subject: [PATCH 7/9] feat: major vercel ai-sdk guide improvement/testing --- docs/competitions/guides/vercel.mdx | 243 ++++++++++++++++------------ 1 file changed, 137 insertions(+), 106 deletions(-) diff --git a/docs/competitions/guides/vercel.mdx b/docs/competitions/guides/vercel.mdx index 17e5eee..51ddc5a 100644 --- a/docs/competitions/guides/vercel.mdx +++ b/docs/competitions/guides/vercel.mdx @@ -1,24 +1,22 @@ --- -title: Serverless Trader with Next.js 13 and Recall -description: Guide to build and deploy a Recall trading bot using Next.js 13, Vercel Functions, and the Vercel AI SDK. +title: AI SDK x Recall trading bot +description: Guide to build and deploy a Recall trading bot using Vercel AI SDK and Next.js. --- -# Introduction +## Introduction Ready to build and deploy a fully serverless AI trading bot—end to end—in under an hour? 🚀 -This hands-on guide shows how to combine **Next.js 13**, **Vercel Functions**, and the **Vercel AI SDK** to create a bot that streams LLM decisions, executes sandbox trades, and runs globally on Vercel’s edge—no backend servers required. +This hands-on guide shows how to combine **Next.js**, **Vercel Functions**, and the **Vercel AI SDK** to create a bot that streams LLM decisions, executes sandbox trades, and runs globally on Vercel’s edge—no backend servers required. Here’s what you’ll accomplish: -1. Scaffold a Next.js 13 project +1. Scaffold a Next.js project 2. Implement an edge function for trade decisions and execution 3. Build a React UI with the AI SDK’s `useChat` hook 4. Test locally, then deploy worldwide with a single command No Recall or Vercel experience required—just bring basic Node and TypeScript skills. Let’s dive in! ---- - -## 1. Prerequisites +## Prerequisites | Requirement | Minimum version | Purpose | |-------------------------|----------------|--------------------------------------| @@ -37,30 +35,34 @@ Need to get set up? Don’t forget to add .env.local to .gitignore—keep those secrets safe! ---- +## Step by step guide + + -## 2. Project Setup + +### Project setup -Let’s spin up your Next.js 13 app with all the right features: +Let’s spin up your Next.js app with all the right features: -### 2.1 Create the Next.js app +#### Create the Next.js app ```bash copy npx create-next-app@latest recall-vercel-bot --ts --app --eslint --tailwind --src-dir cd recall-vercel-bot -```` +``` This sets up TypeScript, app router, ESLint, Tailwind CSS, and puts your code in `src/`. -### 2.2 Install runtime packages +#### Install required packages ```bash copy -npm install ai axios axios-retry +npm install ai axios axios-retry @ai-sdk/openai ``` ---- + -## 3. Environment Variables + +### Set environment variables Store your keys locally in `.env.local` (already git-ignored): @@ -82,77 +84,115 @@ vercel env add RECALL_API_URL With your environment secured, your bot’s trades and LLM prompts stay private and production-ready. ---- + -## 4. Edge Function: `route.ts` + +### Edge function: `route.ts` Now let’s give your bot a brain and a trading hand—with a blazing-fast edge function! Create `src/app/api/trade/route.ts`: ```ts filename="src/app/api/trade/route.ts" showLineNumbers copy -import { OpenAIStream, StreamingTextResponse } from 'ai'; -import OpenAI from 'openai'; -import axios from 'axios'; - -export const runtime = 'edge'; // Next.js Edge Function - -const openai = new OpenAI({ - apiKey: process.env.OPENAI_API_KEY, +import { openai } from "@ai-sdk/openai"; +import { convertToCoreMessages, streamText, tool, UIMessage } from "ai"; +import axios from "axios"; +import { env } from "process"; +import { z } from "zod"; + +// Allow streaming responses up to 30 seconds +export const maxDuration = 30; + +const parameters = z.object({ + fromToken: z + .string() + .describe("Address of token to trade from defaults to USDC") + .optional() + .default("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"), + toToken: z + .string() + .describe("Address of token to trade to defaults to SOL") + .optional() + .default("So11111111111111111111111111111111111111112"), + amount: z + .string() + .describe("Amount in tokens defaults to 10") + .optional() + .default("10"), + reason: z + .string() + .min(10) + .describe("Detailed reason for the trade (required for competition)") + .optional() + .default("Big opportunity"), + slippageTolerance: z + .string() + .optional() + .default("0.5") + .describe("Slippage tolerance percentage (default: 0.5)"), + fromChain: z + .enum(["evm", "svm"]) + .describe("Chain type for from token") + .optional() + .default("svm"), + fromSpecificChain: z + .string() + .describe("Specific chain for the from token") + .optional() + .default("svm"), + toChain: z + .enum(["evm", "svm"]) + .describe("Chain type for to token") + .optional() + .default("svm"), + toSpecificChain: z + .string() + .describe("Specific chain for the to token") + .optional() + .default("svm"), }); export async function POST(req: Request) { - const { prompt } = await req.json(); - - // 1. Use OpenAI to reason about a trade - const completion = await openai.chat.completions.create({ - model: 'gpt-4o-mini', - stream: true, - messages: [ - { - role: 'system', - content: - `Decide whether to buy WETH with 10 USDC on Recall.\n` + - `Return JSON with fields {execute: boolean, reason: string}.`, - }, - { role: 'user', content: prompt }, - ], - }); - - // 2. Stream tokens back to the UI - const stream = OpenAIStream(completion, { - async onFinal(chunk) { - try { - const decision = JSON.parse(chunk); - if (!decision.execute) return; - - // 3. Execute trade on Recall - const { data } = await axios.post( - `${process.env.RECALL_API_URL}/api/trade/execute`, - { - fromToken: - '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC - toToken: - '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', // WETH - amount: '10', - reason: decision.reason, - }, - { + const { messages } = (await req.json()) as { messages: UIMessage[] }; + + const result = streamText({ + model: openai("gpt-4o-mini-2024-07-18"), + messages: convertToCoreMessages(messages.filter((m) => m.role === "user")), + tools: { + recallTrade: tool({ + description: + "Deside whether to buy or sell a given crypto asset asked by the user using Recall-api if not lot of details are provided the tool will use the default parameters. Returns the trade result", + parameters, + execute: async (params: z.infer) => { + // Send the trade to recall api + const http = axios.create({ headers: { - Authorization: `Bearer ${process.env.RECALL_API_KEY}`, + Authorization: `Bearer ${process.env.RECALL_API_KEY!}`, + "Content-Type": "application/json", }, - timeout: 30_000, + }); + try { + const res = await http.post( + `${env.RECALL_API_URL}/api/trade/execute`, + JSON.stringify(params) + ); + const trade = res.data.transaction; + console.log("Recall-api trade result:", trade); + return { + text: `Your trade was executed successfully you bought with ${trade.fromAmount} ${trade.fromTokenSymbol} ${trade.toAmount} ${trade.toTokenSymbol}`, + }; + } catch (error: any) { + return { + text: `There was an error executing the trade. Please try again. ${error.message}`, + }; } - ); - - console.log('Recall trade txHash:', data.txHash); - } catch (err) { - console.error('Trade execution failed:', err); - } + }, + }), }, + maxSteps: 3, + maxRetries: 3, }); - - return new StreamingTextResponse(stream); + return result.toDataStreamResponse(); } ``` @@ -160,37 +200,37 @@ export async function POST(req: Request) { Edge functions run close to your users for low-latency AI and instant trades—no backend server required! ---- + -## 5. React Front‑End + +### React front‑end Let’s give your bot a friendly UI! Create `src/app/page.tsx`: ```tsx filename="src/app/page.tsx" showLineNumbers copy -'use client'; +"use client"; -import { useChat } from 'ai/react'; -import { useState } from 'react'; +import { useChat } from "@ai-sdk/react"; +import { useState } from "react"; export default function Home() { const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({ - api: '/api/trade', + api: "/api/trade", }); - const [status, setStatus] = useState(''); + const [status, setStatus] = useState(""); return (
-

- Recall Serverless Trader -

+

Recall Serverless Trader

{ - handleSubmit(e).then(() => setStatus('Request sent.')); + handleSubmit(e); + setStatus("Request sent."); }} className="flex gap-2" > @@ -220,15 +260,17 @@ export default function Home() {
); } + ``` Your UI is live! Try customizing the prompt or styling for your own brand. ---- +
-## 6. Local Test + +### Local test Ready to see your bot in action? Start the local dev server: @@ -237,7 +279,7 @@ Start the local dev server: npm run dev ``` -Open [http://localhost:3000](http://localhost:3000), and ask “Should we buy now?” in the chat box. +Open [http://localhost:3000](http://localhost:3000), and ask “Buy SOL with 100USDC” in the chat box. Then you can ask “Sell 0.2 SOL for USDC”. **What to expect:** @@ -250,9 +292,10 @@ Trouble connecting? - Still stuck? [Ask for help in the Recall Discord](#) ---- + -## 7. Deploy to Vercel + +### Deploy to Vercel Let’s go global! @@ -267,21 +310,11 @@ The production URL appears at the end—share it or open it right away! 🎉 You just shipped a serverless trading bot to the world! ---- + -## 8. Validate in Recall +
-1. Log in to your [Recall dashboard](https://recall.network). -2. Go to **Orders → Sandbox** to confirm your bot’s trade shows up. -3. Your API key is now whitelisted for live competitions—welcome to Recall! - - -Once you’re whitelisted, you can join live competitions and start climbing the leaderboard. See you there! - - ---- - -## 9. Troubleshooting +## Troubleshooting Hit a snag? You’re not alone—here are common fixes: @@ -297,16 +330,14 @@ Still need help? * [Join the Recall Discord](#) or ask in the Vercel community * Share your code or error logs—someone’s always happy to help! ---- - -## 10. Scalability & Next Steps +## Next steps * **Vercel Cron:** Schedule `/api/trade` POSTs nightly for automated backtests or daily rebalancing. * **Edge Middleware:** Add JWT or session validation for endpoint security. * **Observability:** Pipe AI latency and trade metrics to Vercel Analytics for monitoring. **You did it!** -You’ve built, shipped, and validated a serverless AI trading bot—fully powered by Next.js 13, Vercel Functions, the AI SDK, and Recall. +You’ve built, shipped, and validated a serverless AI trading bot—fully powered by Next.js, Vercel Functions, the AI SDK, and Recall. Join the Recall community, share your build, and take your bot to the leaderboard! Happy hacking! 🚀 From 4ce5273eb566d86b650bd6c8c61a1bfb6fcfc532 Mon Sep 17 00:00:00 2001 From: nijoe1 Date: Wed, 23 Jul 2025 21:13:09 +0300 Subject: [PATCH 8/9] fix: eliza step by step guide --- docs/competitions/guides/eliza.mdx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index bd8bc2b..344418b 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -43,8 +43,11 @@ Need keys? ```bash copy bun i -g @elizaos/cli # ⚡ one-time install elizaos create recall-eliza-bot +# This will ask you to +# Which database would you like to use? use PgLite(default) +# Which AI model would you like to use? use OpenAI cd recall-eliza-bot -bun install # installs deps for the new project +bun install axios # installs deps for the new project ``` The generator scaffolds: @@ -52,7 +55,7 @@ The generator scaffolds: ``` eliza.config.ts # global agent config character.ts # personality & instructions -plugins/ # place for first-party & custom plugins +src/plugins/ # place for first-party & custom plugins ``` @@ -63,7 +66,7 @@ plugins/ # place for first-party & custom plugins Create `.env` at the project root: ```dotenv filename=".env" copy -OPENAI_API_KEY=sk-... +OPENAI_API_KEY=already-set-from-cli RECALL_API_KEY=rk-... RECALL_API_URL=https://api.sandbox.competitions.recall.network ``` @@ -75,10 +78,10 @@ RECALL_API_URL=https://api.sandbox.competitions.recall.network ### Write a Recall trade plugin -Plugins live inside `plugins/*`. -Create `plugins/plugin-recall-trade.ts`: +Plugins live inside `src/plugins/*`. +Create `src/plugins/recall-trade-plugin.ts`: -```ts filename="plugins/plugin-recall-trade.ts" showLineNumbers copy +```ts filename="src/plugins/recall-trade-plugin.ts" showLineNumbers copy import type { Plugin, Action, @@ -244,7 +247,7 @@ import { type ProjectAgent, } from "@elizaos/core"; import { character } from "./character.ts"; -import tradePlugin from "./plugins/plugin-recall-trade.ts"; +import tradePlugin from "./plugins/recall-trade-plugin.ts"; const initCharacter = ({ runtime }: { runtime: IAgentRuntime }) => { logger.info("Initializing character"); @@ -292,7 +295,6 @@ export const character: Character = { ...(!process.env.IGNORE_BOOTSTRAP ? ["@elizaos/plugin-bootstrap"] : []), ], settings: { - model: "gpt-4o-mini", secrets: {}, avatar: "https://elizaos.github.io/eliza-avatars/Eliza/portrait.png", }, From f720df31567049bb1b71ef93580eb1f11fc9c15e Mon Sep 17 00:00:00 2001 From: nijoe1 Date: Wed, 23 Jul 2025 21:21:56 +0300 Subject: [PATCH 9/9] chore: small improvement on eliza guide --- docs/competitions/guides/eliza.mdx | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/competitions/guides/eliza.mdx b/docs/competitions/guides/eliza.mdx index 344418b..869fcfc 100644 --- a/docs/competitions/guides/eliza.mdx +++ b/docs/competitions/guides/eliza.mdx @@ -41,13 +41,13 @@ Need keys? ### Install the eliza CLI & create a project ```bash copy -bun i -g @elizaos/cli # ⚡ one-time install +bun i -g @elizaos/cli # ⚡ one-time install elizaos create recall-eliza-bot -# This will ask you to +# This will prompt you to select the database and the AI model to use. # Which database would you like to use? use PgLite(default) # Which AI model would you like to use? use OpenAI cd recall-eliza-bot -bun install axios # installs deps for the new project +bun install axios # Additional dependency for the project ``` The generator scaffolds: @@ -280,9 +280,9 @@ Open `./src/character.ts`: ```ts filename="src/character.ts" showLineNumbers copy import { type Character } from "@elizaos/core"; /** - * Represents the default character Recall Trader. - * Recall Trader can be extended to become the best trading agent in the trading competitions that are held on the Recall platform. - * Extend him to impove his trading strategies and improve his performance in the trading competitions. + * Represents the default character of your Recall Trader agent. + * Recall Trader can be extended to become the best trading agent on the Recall platform. + * Extend him to impove his trading strategies and improve his performance. */ export const character: Character = { name: "Recall Trader",