Skip to content
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

feat: implement coinbase trading #608

Merged
merged 26 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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
Prev Previous commit
Next Next commit
Tested and working ETH <-> USDC
  • Loading branch information
monilpat committed Nov 28, 2024
commit d9df31ea7f04faa65468a10ed56f4bf8cf1c7909
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,8 @@
"sharp": "^0.33.5",
"tslog": "^4.9.3"
},
"packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee"
"packageManager": "pnpm@9.12.3+sha512.cce0f9de9c5a7c95bef944169cc5dfe8741abfb145078c0d508b868056848a87c81e626246cb60967cbd7fd29a6c062ef73ff840d96b3c86c40ac92cf4a813ee",
"workspaces": [
"packages/*"
]
}
6 changes: 3 additions & 3 deletions packages/core/src/generation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ export const generateCaption = async (
export interface GenerationOptions {
runtime: IAgentRuntime;
context: string;
modelClass: TiktokenModel;
modelClass: ModelClass;
schema?: ZodSchema;
schemaName?: string;
schemaDescription?: string;
Expand Down Expand Up @@ -946,7 +946,7 @@ export const generateObjectV2 = async ({
}

const provider = runtime.modelProvider;
const model = models[provider].model[modelClass];
const model = models[provider].model[modelClass] as TiktokenModel;
if (!model) {
throw new Error(`Unsupported model class: ${modelClass}`);
}
Expand All @@ -958,7 +958,7 @@ export const generateObjectV2 = async ({
const apiKey = runtime.token;

try {
context = trimTokens(context, max_context_length, "gpt-4o");
context = trimTokens(context, max_context_length, model);

const modelOptions: ModelSettings = {
prompt: context,
Expand Down
22 changes: 9 additions & 13 deletions packages/plugin-coinbase/package.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
{
"name": "@ai16z/plugin-coinbase",
"version": "0.1.3",
"version": "0.1.4-alpha.3",
"main": "dist/index.js",
"type": "module",
"types": "dist/index.d.ts",
"dependencies": {
"@ai16z/eliza": "^0.1.3",
"coinbase-api": "1.0.5"
"coinbase-api": "1.0.5",
"@ai16z/eliza": "workspace:*"
},
"devDependencies": {
"eslint": "9.13.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-prettier": "5.2.1",
"eslint-plugin-vitest": "0.5.4",
"tsup": "8.3.5"
},
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --watch"
},
"peerDependencies": {
"onnxruntime-node": "1.20.1",
"vue": "3.5.13",
"whatwg-url": "7.1.0"
},
"trustedDependencies": {
"onnxruntime-node": "^1.20.0",
"sharp": "^0.33.5"
"dev": "tsup --watch",
"lint": "eslint . --fix"
}
}
61 changes: 33 additions & 28 deletions packages/plugin-coinbase/src/plugins/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ export const tradeProvider: Provider = {
path: tradeCsvFilePath,
header: [
"Network",
"Amount",
"From Amount",
"Source Asset",
"To Amount",
"Target Asset",
"Status",
"Error Code",
"Transaction URL",
],
});
Expand All @@ -67,11 +67,11 @@ export const tradeProvider: Provider = {
elizaLogger.log("Parsed CSV records:", records);
return records.map((record: any) => ({
network: record["Network"] || undefined,
amount: parseFloat(record["Amount"]) || undefined,
amount: parseFloat(record["From Amount"]) || undefined,
sourceAsset: record["Source Asset"] || undefined,
toAmount: parseFloat(record["To Amount"]) || undefined,
targetAsset: record["Target Asset"] || undefined,
status: record["Status"] || undefined,
errorCode: record["Error Code"] || "",
transactionUrl: record["Transaction URL"] || "",
}));
} catch (error) {
Expand All @@ -81,37 +81,37 @@ export const tradeProvider: Provider = {
},
};

export async function appendTradesToCsv(trades: TradeTransaction[]) {
export async function appendTradeToCsv(trade: Trade) {
try {
const csvWriter = createArrayCsvWriter({
path: tradeCsvFilePath,
header: [
"Network",
"Amount",
"From Amount",
"Source Asset",
"To Amount",
"Target Asset",
"Status",
"Error Code",
"Transaction URL",
],
append: true,
});

const formattedTrades = trades.map((trade) => [
trade.network,
trade.amount.toString(),
trade.sourceAsset,
trade.targetAsset,
trade.status,
trade.errorCode || "",
trade.transactionUrl || "",
]);
const formattedTrade = [
trade.getNetworkId(),
trade.getFromAmount(),
trade.getFromAssetId(),
trade.getToAmount(),
trade.getToAssetId(),
trade.getStatus(),
trade.getTransaction().getTransactionLink() || "",
];

elizaLogger.log("Writing trades to CSV:", formattedTrades);
await csvWriter.writeRecords(formattedTrades);
elizaLogger.log("All trades written to CSV successfully.");
elizaLogger.log("Writing trade to CSV:", formattedTrade);
await csvWriter.writeRecords([formattedTrade]);
elizaLogger.log("Trade written to CSV successfully.");
} catch (error) {
elizaLogger.error("Error writing trades to CSV:", error);
elizaLogger.error("Error writing trade to CSV:", error);
}
}

Expand Down Expand Up @@ -198,8 +198,8 @@ export const executeTradeAction: Action = {

const tradeParams = {
amount,
fromAssetId: sourceAsset,
toAssetId: targetAsset,
fromAssetId: sourceAsset.toLowerCase(),
toAssetId: targetAsset.toLowerCase(),
};

const trade: Trade = await wallet.createTrade(tradeParams);
Expand All @@ -210,14 +210,15 @@ export const executeTradeAction: Action = {
await trade.wait();

elizaLogger.log("Trade completed successfully:", trade.toString());

await appendTradeToCsv(trade);
callback(
{
text: `Trade executed successfully:
- Network: ${network}
- Amount: ${amount}
- From: ${sourceAsset}
- To: ${targetAsset}`,
- To: ${targetAsset}
- Transaction URL: ${trade.getTransaction().getTransactionLink() || ""}`,
},
[]
);
Expand All @@ -236,7 +237,7 @@ export const executeTradeAction: Action = {
{
user: "{{user1}}",
content: {
text: "Trade 0.0001 ETH for USDC on the base",
text: "Trade 0.00001 ETH for USDC on the base",
},
},
{
Expand All @@ -246,7 +247,8 @@ export const executeTradeAction: Action = {
- Network: base
- Amount: 0.01
- From: ETH
- To: USDC`,
- To: USDC
- Transaction URL: https://www.basescan.com/`,
},
},
],
Expand All @@ -264,7 +266,8 @@ export const executeTradeAction: Action = {
- Network: sol
- Amount: 1
- From: SOL
- To: USDC`,
- To: USDC
- Transaction URL: https://www.solscan.com/`,
},
},
],
Expand All @@ -282,7 +285,8 @@ export const executeTradeAction: Action = {
- Network: pol
- Amount: 100
- From: USDC
- To: ETH`,
- To: ETH
- Transaction URL: https://www.etherscan.com/`,
},
},
],
Expand All @@ -301,4 +305,5 @@ export const tradePlugin: Plugin = {
name: "tradePlugin",
description: "Enables asset trading using the Coinbase SDK.",
actions: [executeTradeAction],
providers: [tradeProvider],
};
9 changes: 7 additions & 2 deletions packages/plugin-coinbase/src/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,13 @@ export const tradeTemplate = `
Extract the following details for processing a trade using the Coinbase SDK:
- **network** (string): The blockchain network to use (e.g., base, sol, eth, arb, pol).
- **amount** (number): The amount to trade (in the smallest unit, e.g., Wei for ETH).
- **sourceAsset** (string): The asset ID to trade from (ETH, SOL, USDC).
- **targetAsset** (string): The asset ID to trade to (ETH, SOL, USDC).
- **sourceAsset** (string): The asset ID to trade from (must be one of: ETH, SOL, USDC, WETH, GWEI, LAMPORT).
- **targetAsset** (string): The asset ID to trade to (must be one of: ETH, SOL, USDC, WETH, GWEI, LAMPORT).

Ensure that:
1. **network** is one of the supported networks: "base", "sol", "eth", "arb", or "pol".
2. **sourceAsset** and **targetAsset** are valid assets from the provided list.
3. **amount** is a positive number.

Provide the details in the following JSON format:

Expand Down
7 changes: 4 additions & 3 deletions packages/plugin-coinbase/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Coinbase } from "@coinbase/coinbase-sdk";
import { z } from "zod";

export const ChargeSchema = z.object({
Expand Down Expand Up @@ -51,12 +52,12 @@ export type Transaction = {
errorCode: string | null;
transactionUrl: string | null;
};

const assetValues = Object.values(Coinbase.assets) as [string, ...string[]];
export const TradeSchema = z.object({
network: z.string().toLowerCase(),
amount: z.number(),
sourceAsset: z.string().toLowerCase(),
targetAsset: z.string().toLowerCase(),
sourceAsset: z.enum(assetValues),
targetAsset: z.enum(assetValues),
leverage: z.number().optional(), // Optional leverage for leveraged trades
});

Expand Down
Loading