Skip to content

feat: Add ethers transaction execution tool #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/ai-agent-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"test:llm": "vitest src/core/llm/llm.test.ts",
"test:tools:goldrush": "vitest src/core/tools/goldrush/index.test.ts",
"test:zee": "vitest src/core/zee/zee.test.ts",
"test:tools:onchain-actions": "vitest src/core/tools/onchain-actions/onchain-actions.test.ts",
"build": "tsc",
"clean": "rm -rf dist",
"prepublishOnly": "cp ../../README.md . && npm run clean && npm run build",
Expand All @@ -51,6 +52,7 @@
"@covalenthq/client-sdk": "^2.2.3",
"commander": "^13.1.0",
"dotenv": "^16.4.7",
"ethers": "5.7",
"openai": "^4.79.1",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { Tool } from "../base";
import { ethers } from "ethers";
import { z } from "zod";

export const ExecuteTransactionSchema = z.object({
rpcUrl: z.string().describe("The RPC URL for the network"),
to: z.string().describe("The recipient address"),
value: z.string().describe("The amount to send in wei"),
});

export type ExecuteTransactionParams = z.infer<typeof ExecuteTransactionSchema>;

export class ExecuteTransactionTool extends Tool {
private readonly privateKey: string;

constructor(privateKey: string) {
if (!privateKey) {
throw new Error("Private key is required");
}

super(
"evm-transaction",
"Execute EVM transactions using a private key",
ExecuteTransactionSchema,
async (parameters) =>
await this.executeTransaction(
parameters as ExecuteTransactionParams
)
);

this.privateKey = privateKey;
}

private async executeTransaction(
params: ExecuteTransactionParams
): Promise<string> {
try {
const provider = new ethers.providers.JsonRpcProvider(
params.rpcUrl
);
const wallet = new ethers.Wallet(this.privateKey, provider);

const tx: ethers.providers.TransactionRequest = {
to: params.to,
value: ethers.BigNumber.from(params.value),
};

const transaction = await wallet.sendTransaction(tx);
const receipt = await transaction.wait();

return JSON.stringify({
status: "success",
transactionHash: receipt.transactionHash,
blockNumber: receipt.blockNumber,
gasUsed: receipt.gasUsed.toString(),
effectiveGasPrice: receipt.effectiveGasPrice.toString(),
});
} catch (error) {
return JSON.stringify({
status: "error",
message:
error instanceof Error
? error.message
: "Unknown error occurred",
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import { Agent } from "../../agent";
import { user } from "../../base";
import { StateFn } from "../../state";
import { runToolCalls } from "../base";
import { ExecuteTransactionTool } from "./execute-transactions";
import "dotenv/config";
import type { ChatCompletionAssistantMessageParam } from "openai/resources";
import { beforeAll, expect, test } from "vitest";

let rpcUrl: string;
let privateKey: string;

beforeAll(() => {
if (!process.env["RPC_URL"]) {
throw new Error("RPC_URL environment variable is not set");
}
if (!process.env["PRIVATE_KEY"]) {
throw new Error("PRIVATE_KEY environment variable is not set");
}
rpcUrl = process.env["RPC_URL"];
privateKey = process.env["PRIVATE_KEY"];
});

test("transaction agent should execute ETH transfers", async () => {
const tools = {
transaction: new ExecuteTransactionTool(privateKey),
};

const agent = new Agent({
name: "transaction executor",
model: {
provider: "OPEN_AI",
name: "gpt-4o-mini",
},
description:
"You are an expert at executing and validating blockchain transactions.",
instructions: [
"Parse transaction parameters from user input",
"Execute transactions using the provided tools",
"Verify transaction success and provide confirmation",
"Handle any errors appropriately",
],
tools,
});

const state = StateFn.root(agent.description);
state.messages.push(
user(
`Send 0.001 ETH to 0x742d35Cc6634C0532925a3b844Bc454e4438f44e using RPC URL ${rpcUrl}`
)
);

const result = await agent.run(state);
console.log(result);
expect(result.status).toEqual("paused");

const toolCall = result.messages[
result.messages.length - 1
] as ChatCompletionAssistantMessageParam;
expect(toolCall?.tool_calls).toBeDefined();

if (toolCall.tool_calls) {
toolCall.tool_calls.forEach((call) => {
if (
call.type === "function" &&
call.function.name === "evm-transaction"
) {
const args = JSON.parse(call.function.arguments);
args.privateKey = privateKey;
call.function.arguments = JSON.stringify(args);
}
});
}

const toolResponses = await runToolCalls(tools, toolCall?.tool_calls ?? []);

const updatedState = {
...result,
status: "running" as const,
messages: [...result.messages, ...toolResponses],
};

const finalResult = await agent.run(updatedState);
console.log(finalResult);

expect(finalResult.status).toEqual("finished");
expect(
finalResult.messages[finalResult.messages.length - 1]?.content
).toBeDefined();

const lastToolResponse = toolResponses[toolResponses.length - 1];
const txResult = JSON.parse(lastToolResponse?.content as string);

expect(txResult.status).toEqual("success");
expect(txResult.transactionHash).toBeDefined();
expect(txResult.blockNumber).toBeDefined();

console.log(
"Transaction Result:",
finalResult.messages[finalResult.messages.length - 1]?.content
);
});

test("transaction agent should handle failed transactions", async () => {
const tools = {
transaction: new ExecuteTransactionTool(privateKey),
};

const agent = new Agent({
name: "transaction executor",
model: {
provider: "OPEN_AI",
name: "gpt-4o-mini",
},
description:
"You are an expert at executing and validating blockchain transactions.",
instructions: [
"Parse transaction parameters from user input",
"Execute transactions using the provided tools",
"Verify transaction success and provide confirmation",
"Handle any errors appropriately",
],
tools,
});

const state = StateFn.root(agent.description);
state.messages.push(
user(
`Send 1000000 ETH to 0x742d35Cc6634C0532925a3b844Bc454e4438f44e using RPC URL ${rpcUrl}`
)
);

const result = await agent.run(state);
expect(result.status).toEqual("paused");

const toolCall = result.messages[
result.messages.length - 1
] as ChatCompletionAssistantMessageParam;
expect(toolCall?.tool_calls).toBeDefined();

if (toolCall.tool_calls) {
toolCall.tool_calls.forEach((call) => {
if (
call.type === "function" &&
call.function.name === "evm-transaction"
) {
const args = JSON.parse(call.function.arguments);
args.privateKey = privateKey;
call.function.arguments = JSON.stringify(args);
}
});
}

const toolResponses = await runToolCalls(tools, toolCall?.tool_calls ?? []);

const updatedState = {
...result,
status: "running" as const,
messages: [...result.messages, ...toolResponses],
};

const finalResult = await agent.run(updatedState);

expect(finalResult.status).toEqual("finished");

const lastToolResponse = toolResponses[toolResponses.length - 1];
const txResult = JSON.parse(lastToolResponse?.content as string);

expect(txResult.status).toEqual("error");
expect(txResult.message).toBeDefined();

console.log(
"Error Handling Result:",
finalResult.messages[finalResult.messages.length - 1]?.content
);
});
Loading
Loading