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

Filipposl/coingecko plugin #10

Merged
merged 7 commits into from
Dec 6, 2024
Merged
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
4 changes: 4 additions & 0 deletions typescript/examples/vercel-ai/coingecko/.env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
OPENAI_API_KEY=
WALLET_PRIVATE_KEY=
ALCHEMY_API_KEY=
COINGECKO_API_KEY=
15 changes: 15 additions & 0 deletions typescript/examples/vercel-ai/coingecko/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Vercel AI with viem Example

## Setup

Copy the `.env.template` and populate with your values.

```
cp .env.template .env
```

## Usage

```
npx ts-node index.ts
```
46 changes: 46 additions & 0 deletions typescript/examples/vercel-ai/coingecko/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { openai } from "@ai-sdk/openai";
import { generateText } from "ai";

import { http } from "viem";
import { createWalletClient } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { sepolia } from "viem/chains";

import { getOnChainTools } from "@goat-sdk/adapter-vercel-ai";
import { PEPE, USDC, erc20 } from "@goat-sdk/plugin-erc20";

import { viem } from "@goat-sdk/wallet-viem";
import { sendETH } from "@goat-sdk/core";
import { coingecko } from "@goat-sdk/plugin-coingecko";

require("dotenv").config();

const account = privateKeyToAccount(
process.env.WALLET_PRIVATE_KEY as `0x${string}`,
);

const walletClient = createWalletClient({
account: account,
transport: http(process.env.ALCHEMY_API_KEY),
chain: sepolia,
});

(async () => {
const tools = await getOnChainTools({
wallet: viem(walletClient),
plugins: [
sendETH(),
erc20({ tokens: [USDC, PEPE] }),
coingecko({ apiKey: process.env.COINGECKO_API_KEY as string }),
],
});

const result = await generateText({
model: openai("gpt-4o-mini"),
tools: tools,
maxSteps: 5,
prompt: "What are the trending cryptocurrencies right now and what's the price of Bonk?",
});

console.log(result.text);
})();
25 changes: 25 additions & 0 deletions typescript/examples/vercel-ai/coingecko/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "goat-examples-vercel-ai-coingecko",
"version": "0.1.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"@ai-sdk/openai": "^1.0.4",
"@goat-sdk/adapter-vercel-ai": "workspace:*",
"@goat-sdk/core": "workspace:*",
"@goat-sdk/plugin-coingecko": "workspace:*",
"@goat-sdk/plugin-erc20": "workspace:*",
"@goat-sdk/wallet-viem": "workspace:*",
"ai": "^4.0.3",
"dotenv": "^16.4.5",
"viem": "2.21.49"
},
"devDependencies": {
"@types/node": "^22.7.4"
}
}
8 changes: 8 additions & 0 deletions typescript/examples/vercel-ai/coingecko/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "dist"
},
"include": ["index.ts"],
"exclude": ["node_modules", "dist"]
}
2 changes: 1 addition & 1 deletion typescript/examples/vercel-ai/viem/.env.template
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
OPENAI_API_KEY=
WALLET_PRIVATE_KEY=
ALCHEMY_API_KEY=
ALCHEMY_API_KEY=
28 changes: 15 additions & 13 deletions typescript/examples/vercel-ai/viem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,19 @@ const walletClient = createWalletClient({
});

(async () => {
const tools = await getOnChainTools({
wallet: viem(walletClient),
plugins: [sendETH(), erc20({ tokens: [USDC, PEPE] })],
});

const result = await generateText({
model: openai("gpt-4o-mini"),
tools: tools,
maxSteps: 5,
prompt: "Get my balance in USDC",
});

console.log(result.text);
const tools = await getOnChainTools({
wallet: viem(walletClient),
plugins: [
sendETH(),
erc20({ tokens: [USDC, PEPE] })],
});

const result = await generateText({
model: openai("gpt-4o-mini"),
tools: tools,
maxSteps: 5,
prompt: "Get my balance in USDC",
});

console.log(result.text);
})();
36 changes: 36 additions & 0 deletions typescript/packages/plugins/coingecko/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Goat Coingecko Plugin 🐐 - TypeScript

Coingecko plugin for Goat. Allows you to create tools for interacting with the CoinGecko API.

## Installation
```
npm install @goat-sdk/plugin-coingecko
```

## Setup

```typescript
import { coingecko } from "@goat-sdk/plugin-coingecko";

const plugin = coingecko({
apiKey: process.env.COINGECKO_API_KEY
});
```

## Available Actions

### Get Trending Coins
Fetches the current trending cryptocurrencies.

### Get Coin Price
Fetches the current price and optional market data for a specific cryptocurrency.

## Goat

<div align="center">
Go out and eat some grass.

[Docs](https://ohmygoat.dev) | [Examples](https://github.com/goat-sdk/goat/tree/main/typescript/examples) | [Discord](https://discord.gg/goat-sdk)</div>

## Goat 🐐
Goat 🐐 (Great Onchain Agent Toolkit) is an open-source library enabling AI agents to interact with blockchain protocols and smart contracts via their own wallets.
48 changes: 48 additions & 0 deletions typescript/packages/plugins/coingecko/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@goat-sdk/plugin-coingecko",
"version": "0.1.7",
"files": ["dist/**/*", "README.md", "package.json"],
"scripts": {
"build": "tsup",
"clean": "rm -rf dist",
"test": "vitest"
},
"sideEffects": false,
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"devDependencies": {
"@types/node": "^22.7.4",
"globals": "^15.12.0",
"ts-node": "^10.9.2",
"tsup": "^8.3.5",
"typescript": "^5.6.3",
"vitest": "^2.1.5"
},
"dependencies": {
"@goat-sdk/core": "workspace:*",
"viem": "^2.21.49",
"zod": "^3.23.8"
},
"peerDependencies": {
"@goat-sdk/core": "workspace:*",
"viem": "^2.21.49"
},
"engines": {
"node": ">=20.12.2 <21",
"npm": "please-use-pnpm",
"pnpm": ">=9",
"yarn": "please-use-pnpm"
},
"homepage": "https://ohmygoat.dev",
"repository": {
"type": "git",
"url": "git+https://github.com/goat-sdk/goat.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/goat-sdk/goat/issues"
},
"keywords": ["ai", "agents", "web3"],
"packageManager": "[email protected]"
}
17 changes: 17 additions & 0 deletions typescript/packages/plugins/coingecko/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Chain, EVMWalletClient, Plugin } from "@goat-sdk/core";
import { getTools } from "./tools";

export function coingecko(credentials: {
apiKey: string;
}): Plugin<any> {
return {
name: "coingecko",
supportsChain: () => true,
supportsSmartWallets: () => true,
getTools: async () => {
return getTools({
apiKey: credentials.apiKey,
});
},
};
}
37 changes: 37 additions & 0 deletions typescript/packages/plugins/coingecko/src/parameters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { z } from "zod";

export const getTrendingCoinsParametersSchema = z.object({
limit: z.number().optional().describe("The number of trending coins to return. Defaults to all coins."),
include_platform: z.boolean().optional().describe("Include platform contract addresses (e.g., ETH, BSC) in response"),
});

export const getCoinPriceParametersSchema = z.object({
coinId: z.string().describe("The ID of the coin on CoinGecko (e.g., 'bitcoin', 'ethereum')"),
vsCurrency: z.string()
.default("usd")
.describe("The target currency to get price in (e.g., 'usd', 'eur', 'jpy')"),
includeMarketCap: z.boolean()
.optional()
.default(false)
.describe("Include market cap data in the response"),
include24hrVol: z.boolean()
.optional()
.default(false)
.describe("Include 24 hour volume data in the response"),
include24hrChange: z.boolean()
.optional()
.default(false)
.describe("Include 24 hour price change data in the response"),
includeLastUpdatedAt: z.boolean()
.optional()
.default(false)
.describe("Include last updated timestamp in the response"),
});

export const searchCoinsParametersSchema = z.object({
query: z.string().describe("The search query to find coins (e.g., 'bitcoin' or 'btc')"),
exact_match: z.boolean()
.optional()
.default(false)
.describe("Only return exact matches for the search query"),
});
77 changes: 77 additions & 0 deletions typescript/packages/plugins/coingecko/src/tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import type { DeferredTool, WalletClient } from "@goat-sdk/core";
import type { z } from "zod";

import {
getTrendingCoinsParametersSchema,
getCoinPriceParametersSchema,
} from "./parameters";

// Define methods to interact with CoinGecko API
async function fetchTrendingCoins(apiKey: string) {
const response = await fetch(`https://api.coingecko.com/api/v3/search/trending?x_cg_demo_api_key=${apiKey}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}

async function fetchCoinPrice(coinId: string, vsCurrency: string, apiKey: string, options: {
includeMarketCap: boolean;
include24hrVol: boolean;
include24hrChange: boolean;
includeLastUpdatedAt: boolean;
}) {
const params = new URLSearchParams({
ids: coinId,
vs_currencies: vsCurrency,
include_market_cap: options.includeMarketCap.toString(),
include_24hr_vol: options.include24hrVol.toString(),
include_24hr_change: options.include24hrChange.toString(),
include_last_updated_at: options.includeLastUpdatedAt.toString(),
});
const response = await fetch(`https://api.coingecko.com/api/v3/simple/price?${params.toString()}&x_cg_demo_api_key=${apiKey}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}

export function getTools(credentials: {
apiKey: string;
}): DeferredTool<any>[] {
const tools: DeferredTool<any>[] = [];

const getTrendingCoinsTool: DeferredTool<any> = {
name: 'get_trending_coins',
filipposl marked this conversation as resolved.
Show resolved Hide resolved
description: 'This {{tool}} fetches the list of trending coins from CoinGecko',
parameters: getTrendingCoinsParametersSchema,
method: async () => fetchTrendingCoins(credentials.apiKey),
};

const getCoinPriceTool: DeferredTool<any> = {
name: 'get_coin_price',
description: 'This {{tool}} fetches the price of a specific coin from CoinGecko',
parameters: getCoinPriceParametersSchema,
method: async (
_client: WalletClient,
parameters: z.infer<typeof getCoinPriceParametersSchema>
) => fetchCoinPrice(
parameters.coinId,
parameters.vsCurrency,
credentials.apiKey,
{
includeMarketCap: parameters.includeMarketCap,
include24hrVol: parameters.include24hrVol,
include24hrChange: parameters.include24hrChange,
includeLastUpdatedAt: parameters.includeLastUpdatedAt,
}
),
};

tools.push(
getTrendingCoinsTool,
getCoinPriceTool
);

return tools;
}
6 changes: 6 additions & 0 deletions typescript/packages/plugins/coingecko/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../../tsconfig.base.json",
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
6 changes: 6 additions & 0 deletions typescript/packages/plugins/coingecko/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineConfig } from "tsup";
import { treeShakableConfig } from "../../../tsup.config.base";

export default defineConfig({
...treeShakableConfig,
});
16 changes: 16 additions & 0 deletions typescript/packages/plugins/coingecko/turbo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"inputs": [
"src/**",
"tsup.config.ts",
"!./**/*.test.{ts,tsx}",
"tsconfig.json"
],
"dependsOn": ["^build"],
"outputs": ["dist/**"]
}
}
}
Loading
Loading