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

fix: plugin-0x #3178

Merged
merged 4 commits into from
Feb 2, 2025
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
41 changes: 41 additions & 0 deletions packages/plugin-0x/biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "https://biomejs.dev/schemas/1.5.3/schema.json",
"organizeImports": {
"enabled": false
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"correctness": {
"noUnusedVariables": "error"
},
"suspicious": {
"noExplicitAny": "error"
},
"style": {
"useConst": "error",
"useImportType": "off"
}
}
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 4,
"lineWidth": 100
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"trailingCommas": "es5"
}
},
"files": {
"ignore": [
"dist/**/*",
"extra/**/*",
"node_modules/**/*"
]
}
}
12 changes: 10 additions & 2 deletions packages/plugin-0x/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,21 @@
"scripts": {
"build": "tsup --format esm --dts",
"dev": "tsup --format esm --dts --watch",
"test": "vitest run"
"test": "vitest run",
"lint": "biome check src/",
"lint:fix": "biome check --apply src/",
"format": "biome format src/",
"format:fix": "biome format --write src/"
},
"dependencies": {
"@elizaos/core": "workspace:*",
"whatwg-url": "7.1.0",
"@0x/swap-ts-sdk": "2.1.1"
},
"devDependencies": {
"tsup": "^8.0.1"
"tsup": "^8.0.1",
"@biomejs/biome": "1.5.3",
"vitest": "^2.1.5"
},
"peerDependencies": {
"@elizaos/core": "workspace:*",
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-0x/src/EVMtokenRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { elizaLogger } from "@elizaos/core";
import {
Chains,
TokenMetadata,
TrustWalletGithubJson,
TrustWalletTokenMetadata,
type TokenMetadata,
type TrustWalletGithubJson,
type TrustWalletTokenMetadata,
} from "./types";
import { NATIVE_TOKENS } from "./constants";

Expand Down
30 changes: 15 additions & 15 deletions packages/plugin-0x/src/actions/getIndicativePrice.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
Action,
IAgentRuntime,
Memory,
State,
HandlerCallback,
type Action,
type IAgentRuntime,
type Memory,
type State,
type HandlerCallback,
elizaLogger,
composeContext,
ModelClass,
Expand All @@ -13,7 +13,7 @@ import {
import { createClientV2 } from "@0x/swap-ts-sdk";
import { getIndicativePriceTemplate } from "../templates";
import { z } from "zod";
import { Chains, GetIndicativePriceResponse, PriceInquiry } from "../types";
import { Chains, type GetIndicativePriceResponse, type PriceInquiry } from "../types";
import { parseUnits } from "viem";
import { CHAIN_NAMES, ZX_MEMORY } from "../constants";
import { EVMTokenRegistry } from "../EVMtokenRegistry";
Expand Down Expand Up @@ -45,17 +45,17 @@ export const getIndicativePrice: Action = {
runtime: IAgentRuntime,
message: Memory,
state: State,
options: Record<string, unknown>,
_options: Record<string, unknown>,
callback: HandlerCallback
) => {
const supportedChains = Object.keys(Chains).join(" | ");

state = !state
const localState = !state
? await runtime.composeState(message, { supportedChains })
: await runtime.updateRecentMessageState(state);

const context = composeContext({
state,
state: localState,
template: getIndicativePriceTemplate,
});

Expand Down Expand Up @@ -86,7 +86,7 @@ export const getIndicativePrice: Action = {
text: `Unsupported chain: ${chain}. Supported chains are: ${Object.keys(
Chains
)
.filter((k) => isNaN(Number(k)))
.filter((k) => !Number.isNaN(Number(k)))
.join(", ")}`,
});
return;
Expand Down Expand Up @@ -148,10 +148,10 @@ export const getIndicativePrice: Action = {
// Format amounts to human-readable numbers
const buyAmount =
Number(price.buyAmount) /
Math.pow(10, buyTokenMetadata.decimals);
(10 ** buyTokenMetadata.decimals);
const sellAmount =
Number(price.sellAmount) /
Math.pow(10, sellTokenMetadata.decimals);
(10 ** sellTokenMetadata.decimals);

await storePriceInquiryToMemory(runtime, message, {
sellTokenObject: sellTokenMetadata,
Expand All @@ -163,13 +163,13 @@ export const getIndicativePrice: Action = {

// Updated formatted response to include chain
const formattedResponse = [
`💱 Swap Details:`,
`────────────────`,
"💱 Swap Details:",
"────────────────",
`📤 Sell: ${sellAmount.toFixed(4)} ${sellTokenMetadata.symbol}`,
`📥 Buy: ${buyAmount.toFixed(4)} ${buyTokenMetadata.symbol}`,
`📊 Rate: 1 ${sellTokenMetadata.symbol} = ${(buyAmount / sellAmount).toFixed(4)} ${buyTokenMetadata.symbol}`,
`🔗 Chain: ${CHAIN_NAMES[chainId]}`,
`────────────────`,
"────────────────",
`💫 Happy with the price? Type 'quote' to continue`,
].join("\n");

Expand Down
54 changes: 27 additions & 27 deletions packages/plugin-0x/src/actions/getQuote.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import {
Action,
IAgentRuntime,
Memory,
State,
HandlerCallback,
type Action,
type IAgentRuntime,
type Memory,
type State,
type HandlerCallback,
elizaLogger,
MemoryManager,
} from "@elizaos/core";
import { GetQuoteResponse, PriceInquiry, Quote } from "../types";
import type { GetQuoteResponse, PriceInquiry, Quote } from "../types";
import { formatTokenAmount } from "../utils";
import { CHAIN_NAMES, NATIVE_TOKENS, ZX_MEMORY } from "../constants";
import { createClientV2 } from "@0x/swap-ts-sdk";
Expand All @@ -25,8 +25,8 @@ export const getQuote: Action = {
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
options: Record<string, unknown>,
_state: State,
_options: Record<string, unknown>,
callback: HandlerCallback
) => {
const latestPriceInquiry = await retrieveLatestPriceInquiry(
Expand Down Expand Up @@ -89,7 +89,7 @@ export const getQuote: Action = {
const warnings = [];
if (quote.issues?.balance) {
warnings.push(
`⚠️ Warnings:`,
"⚠️ Warnings:",
` • Insufficient balance (Have ${formatTokenAmount(
quote.issues.balance.actual,
quote.issues.balance.token,
Expand All @@ -99,8 +99,8 @@ export const getQuote: Action = {
}

const formattedResponse = [
`🎯 Firm Quote Details:`,
`────────────────`,
"🎯 Firm Quote Details:",
"────────────────",
// Basic swap details (same as price)
`📤 Sell: ${formatTokenAmount(
quote.sellAmount,
Expand All @@ -125,7 +125,7 @@ export const getQuote: Action = {
)}`,

// Fee breakdown
`💰 Fees Breakdown:`,
"💰 Fees Breakdown:",
` • 0x Protocol Fee: ${formatTokenAmount(
quote.fees.zeroExFee?.amount,
quote.fees.zeroExFee?.token,
Expand Down Expand Up @@ -153,8 +153,8 @@ export const getQuote: Action = {

...(warnings.length > 0 ? warnings : []),

`────────────────`,
`💫 Ready to execute? Type 'execute' to continue`,
"────────────────",
"💫 Ready to execute? Type 'execute' to continue",
]
.filter(Boolean)
.join("\n");
Expand Down Expand Up @@ -223,20 +223,20 @@ export const getQuote: Action = {
],
};

const formatTime = (time: string) => {
const expirationDate = new Date(parseInt(time) * 1000);
// const formatTime = (time: string) => {
// const expirationDate = new Date(parseInt(time) * 1000);

// Format: "Mar 15, 2:30 PM"
const formattedTime = expirationDate.toLocaleString(undefined, {
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
hour12: true,
});
// // Format: "Mar 15, 2:30 PM"
// const formattedTime = expirationDate.toLocaleString(undefined, {
// month: "short",
// day: "numeric",
// hour: "numeric",
// minute: "2-digit",
// hour12: true,
// });

return `${formattedTime}`;
};
// return `${formattedTime}`;
// };

export const retrieveLatestPriceInquiry = async (
runtime: IAgentRuntime,
Expand All @@ -260,7 +260,7 @@ export const retrieveLatestPriceInquiry = async (
}
return null;
} catch (error) {
elizaLogger.error(`Failed to retrieve price inquiry: ${error.message}`);
elizaLogger.error("Failed to retrieve price inquiry:", error.message);
return null;
}
};
Expand Down
29 changes: 14 additions & 15 deletions packages/plugin-0x/src/actions/swap.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import {
Action,
IAgentRuntime,
Memory,
State,
HandlerCallback,
type Action,
type IAgentRuntime,
type Memory,
type State,
type HandlerCallback,
elizaLogger,
MemoryManager,
} from "@elizaos/core";
import { Hex, numberToHex, concat } from "viem";
import { type Hex, numberToHex, concat } from "viem";
import { CHAIN_EXPLORERS, ZX_MEMORY } from "../constants";
import { getWalletClient } from "../hooks.ts/useGetWalletClient";
import { Quote } from "../types";
import type { Quote } from "../types";

export const swap: Action = {
name: "EXECUTE_SWAP_0X",
Expand All @@ -31,8 +31,8 @@ export const swap: Action = {
handler: async (
runtime: IAgentRuntime,
message: Memory,
state: State,
options: Record<string, unknown>,
_state: State,
_options: Record<string, unknown>,
callback: HandlerCallback
) => {
const latestQuote = await retrieveLatestQuote(runtime, message);
Expand Down Expand Up @@ -99,13 +99,12 @@ export const swap: Action = {
content: { hash: txHash, status: "success" },
});
return true;
} else {
callback({
text: `❌ Swap failed! Check transaction: ${CHAIN_EXPLORERS[chainId]}/tx/${txHash}`,
content: { hash: txHash, status: "failed" },
});
return false;
}
callback({
text: `❌ Swap failed! Check transaction: ${CHAIN_EXPLORERS[chainId]}/tx/${txHash}`,
content: { hash: txHash, status: "failed" },
});
return false;
} catch (error) {
elizaLogger.error("Swap execution failed:", error);
callback({
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-0x/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Chains, TokenMetadata } from "./types";
import { Chains, type TokenMetadata } from "./types";

export const ZX_MEMORY = {
price: {
Expand Down
4 changes: 2 additions & 2 deletions packages/plugin-0x/src/hooks.ts/useGetWalletClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import {
http,
publicActions,
createTestClient,
WalletClient,
PublicClient,
type WalletClient,
type PublicClient,
walletActions,
} from "viem";

Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-0x/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Plugin } from "@elizaos/core";
import type { Plugin } from "@elizaos/core";
import { getIndicativePrice } from "./actions/getIndicativePrice";
import { getQuote } from "./actions/getQuote";
import { swap } from "./actions/swap";
Expand Down
Loading