Skip to content

Commit

Permalink
Merge pull request #357 from Sifchain/addPnlBalanceProviders
Browse files Browse the repository at this point in the history
  • Loading branch information
monilpat authored Feb 7, 2025
2 parents 9487683 + 52dfe84 commit ab48055
Show file tree
Hide file tree
Showing 4 changed files with 1,751 additions and 1,434 deletions.
98 changes: 79 additions & 19 deletions packages/client-coinbase/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,34 @@ import {
generateText,
ModelClass,
State,
UUID
UUID,
Provider,
} from "@elizaos/core";
import { postTweet } from "@elizaos/plugin-twitter";
import express from "express";
import { blockExplorerBaseAddressUrl, blockExplorerBaseTxUrl, WebhookEvent } from "./types";
import {
blockExplorerBaseAddressUrl,
blockExplorerBaseTxUrl,
WebhookEvent,
} from "./types";
import { Coinbase, Wallet } from "@coinbase/coinbase-sdk";
import { initializeWallet, readContractWrapper, type CoinbaseWallet } from "@elizaos/plugin-coinbase";
import {
initializeWallet,
readContractWrapper,
type CoinbaseWallet,
} from "@elizaos/plugin-coinbase";
import { tokenSwap } from "@elizaos/plugin-0x";
import { createWalletClient, erc20Abi, http, publicActions } from "viem";
import { getPriceInquiry } from "../../plugin-0x/src/actions/getIndicativePrice";
import { getQuoteObj } from "../../plugin-0x/src/actions/getQuote";
import { privateKeyToAccount } from "viem/accounts";
import { base } from "viem/chains";

export type WalletType = 'short_term_trading' | 'long_term_trading' | 'dry_powder' | 'operational_capital';
export type WalletType =
| "short_term_trading"
| "long_term_trading"
| "dry_powder"
| "operational_capital";

export class CoinbaseClient implements Client {
private runtime: IAgentRuntime;
Expand All @@ -35,6 +48,10 @@ export class CoinbaseClient implements Client {

constructor(runtime: IAgentRuntime) {
this.runtime = runtime;
// add providers to runtime
this.runtime.providers.push(pnlProvider);
this.runtime.providers.push(balanceProvider);
this.runtime.providers.push(addressProvider);
this.server = express();
this.port = Number(runtime.getSetting("COINBASE_WEBHOOK_PORT")) || 3001;
this.wallets = [];
Expand Down Expand Up @@ -469,6 +486,28 @@ export const calculateOverallPNL = async (
initialBalance: number
): Promise<string> => {
elizaLogger.info(`initialBalance ${initialBalance}`);
const totalBalanceUSD = await getTotalBalanceUSD(runtime, publicKey);
elizaLogger.info(`totalBalanceUSD ${totalBalanceUSD}`);
const pnlUSD = totalBalanceUSD - initialBalance;
elizaLogger.info(`pnlUSD ${pnlUSD}`);
const absoluteValuePNL = Math.abs(pnlUSD);
elizaLogger.info(`absoluteValuePNL ${absoluteValuePNL}`);
const formattedPNL = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(absoluteValuePNL);
elizaLogger.info("formattedPNL ", formattedPNL);
const formattedPNLUSD = `${pnlUSD < 0 ? "-" : ""}${formattedPNL}`;
elizaLogger.info("formattedPNLUSD ", formattedPNLUSD);
return formattedPNLUSD;
};

export async function getTotalBalanceUSD(
runtime: IAgentRuntime,
publicKey: `0x${string}`
): Promise<number> {
const client = createWalletClient({
account: privateKeyToAccount(
("0x" + runtime.getSetting("WALLET_PRIVATE_KEY")) as `0x${string}`
Expand Down Expand Up @@ -506,20 +545,41 @@ export const calculateOverallPNL = async (
);
const usdcBalance = Number(usdcBalanceBaseUnits) / 1e6;
elizaLogger.info(`usdcBalance ${usdcBalance}`);
const pnlUSD = ethBalanceUSD + usdcBalance - initialBalance;
elizaLogger.info(`pnlUSD ${pnlUSD}`);
const absoluteValuePNL = Math.abs(pnlUSD);
elizaLogger.info(`absoluteValuePNL ${absoluteValuePNL}`);
const formattedPNL = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(absoluteValuePNL);
elizaLogger.info("formattedPNL ", formattedPNL);
const formattedPNLUSD = `${pnlUSD < 0 ? "-" : ""}${formattedPNL}`;
elizaLogger.info("formattedPNLUSD ", formattedPNLUSD);
return formattedPNLUSD;
return ethBalanceUSD + usdcBalance;
}

export const pnlProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
elizaLogger.debug("Starting pnlProvider.get function");
try {
const pnl = await calculateOverallPNL(
runtime,
runtime.getSetting("WALLET_PUBLIC_KEY") as `0x${string}`,
1000
);
elizaLogger.info("pnl ", pnl);
return `PNL: ${pnl}`;
} catch (error) {
elizaLogger.error("Error in pnlProvider: ", error.message);
return [];
}
},
};

export const balanceProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
const totalBalanceUSD = await getTotalBalanceUSD(
runtime,
runtime.getSetting("WALLET_PUBLIC_KEY") as `0x${string}`
);
return `Total balance: $${totalBalanceUSD.toFixed(2)}`;
},
};

export const addressProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
return `Address: ${runtime.getSetting("WALLET_PUBLIC_KEY")}`;
},
};

export default CoinbaseClientInterface;
export default CoinbaseClientInterface;
12 changes: 8 additions & 4 deletions packages/client-coinbase/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
export interface WebhookEvent {
event: 'buy' | 'sell';
event: "buy" | "sell";
ticker: string;
price: number;
timestamp: number;
metadata?: Record<string, any>;
}

export interface TradeAction {
type: 'BUY' | 'SELL';
type: "BUY" | "SELL";
ticker: string;
amount: number;
price?: number;
}

export const blockExplorerBaseTxUrl = (txHash: string) => `https://basescan.org/tx/${txHash}`
export const blockExplorerBaseAddressUrl = (address: string) => `https://basescan.org/address/${address}`
export const blockExplorerBaseTxUrl = (txHash: string) =>
`https://basescan.org/tx/${txHash}`;
export const blockExplorerBaseAddressUrl = (address: string) =>
`https://basescan.org/address/${address}`;

export const supportedTickers = ["ETH", "WETH"];
3 changes: 0 additions & 3 deletions packages/plugin-0x/src/actions/getQuote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,6 @@ export const formatRouteInfo = (quote: GetQuoteResponse): string[] => {
};

export const getQuoteObj = async (runtime: IAgentRuntime, priceInquiry: PriceInquiry, address: string) => {
elizaLogger.info('inside of getQuoteObj')
// elizaLogger.info('priceInquiry ', JSON.stringify(priceInquiry))
const {
sellTokenObject,
sellAmountBaseUnits,
Expand All @@ -361,7 +359,6 @@ export const getQuoteObj = async (runtime: IAgentRuntime, priceInquiry: PriceInq
chainId: chainId,
taker: address,
})) as GetQuoteResponse;
elizaLogger.info("Quote:", quote);
if (!quote.liquidityAvailable) {
elizaLogger.info("No liquidity available for this swap. Please try again with a different token or amount.");
return;
Expand Down
Loading

0 comments on commit ab48055

Please sign in to comment.