Skip to content

Commit

Permalink
Merge pull request #359 from Sifchain/fixPNLHashPriceInquiry
Browse files Browse the repository at this point in the history
fix: Fix pnl hash price inquiry remove unnecessary logs
  • Loading branch information
monilpat authored Feb 8, 2025
2 parents ab48055 + 8132a8f commit f90f78d
Show file tree
Hide file tree
Showing 9 changed files with 34 additions and 62 deletions.
53 changes: 21 additions & 32 deletions packages/client-coinbase/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ export class CoinbaseClient implements Client {
async initialize(): Promise<void> {
elizaLogger.info("Initializing Coinbase client");
try {
elizaLogger.info("Coinbase client initialized successfully");
// await this.initializeWallets();
elizaLogger.info("Wallets initialized successfully");
await this.setupWebhookEndpoint();
Expand Down Expand Up @@ -221,10 +220,8 @@ Trade specifics:
- Amount traded: $${amountInCurrency.toFixed(2)}
- Price at trade: $${Number(event.price).toFixed(2)}
- Timestamp: ${formattedTimestamp}
- Txn: ${blockExplorerBaseTxUrl(hash)}
- PNL: ${pnl}
Guidelines:
1. Keep it under 180 characters
1. Keep it under 80 characters
2. Include 1-2 relevant emojis
3. Avoid hashtags
4. Use varied wording for freshness
Expand All @@ -235,18 +232,18 @@ Guidelines:
Sample buy tweets:
"📈 Added $${amountInCurrency.toFixed(2)} of ${event.ticker} at $${Number(
event.price
).toFixed(2)}. Overall PNL: ${pnl} ${blockExplorerBaseTxUrl(hash)}"
).toFixed(2)}."
"🎯 Strategic ${event.ticker} buy: $${amountInCurrency.toFixed(2)} at $${Number(
event.price
).toFixed(2)}. Overall PNL: ${pnl} ${blockExplorerBaseTxUrl(hash)}"
).toFixed(2)}."
Sample sell tweets:
"💫 Sold ${event.ticker}: $${amountInCurrency.toFixed(2)} at $${Number(
event.price
).toFixed(2)}. Overall PNL: ${pnl} ${blockExplorerBaseTxUrl(hash)}"
).toFixed(2)}."
"📊 Sold $${amountInCurrency.toFixed(2)} of ${event.ticker} at $${Number(
event.price
).toFixed(2)}. Overall PNL: ${pnl} ${blockExplorerBaseTxUrl(hash)}"
).toFixed(2)}."
Generate only the tweet text, no commentary or markdown.`;
const context = composeContext({
Expand All @@ -261,9 +258,10 @@ Generate only the tweet text, no commentary or markdown.`;
});

const trimmedContent = tweetContent.trim();
return trimmedContent.length > 180
? trimmedContent.substring(0, 177) + "..."
: trimmedContent;
const finalContent = `${trimmedContent} PNL: ${pnl} ${blockExplorerBaseTxUrl(hash)}`;
return finalContent.length > 180
? finalContent.substring(0, 177) + "..."
: finalContent;
} catch (error) {
elizaLogger.error("Error generating tweet content:", error);
const amount =
Expand All @@ -288,21 +286,24 @@ Generate only the tweet text, no commentary or markdown.`;
// Get trading amount from settings
const amount =
Number(this.runtime.getSetting("COINBASE_TRADING_AMOUNT")) ?? 1;
elizaLogger.info("amount ", amount);

// Create and store memory of trade
const memory = this.createTradeMemory(event, amount, roomId);
elizaLogger.info("memory ", memory);
await this.runtime.messageManager.createMemory(memory);

// Generate state and format timestamp
const state = await this.runtime.composeState(memory);
const formattedTimestamp = this.getFormattedTimestamp();
elizaLogger.info("formattedTimestamp ", formattedTimestamp);

// Execute token swap
const buy = event.event.toUpperCase() === "BUY";
const amountInCurrency = buy ? amount : amount / Number(event.price);
const pnl = await calculateOverallPNL(
this.runtime,
this.runtime.getSetting("WALLET_PUBLIC_KEY") as `0x${string}`,
1000
);
elizaLogger.info("pnl ", pnl);
const txHash = await this.executeTokenSwap(
event,
amountInCurrency,
Expand All @@ -314,13 +315,6 @@ Generate only the tweet text, no commentary or markdown.`;
}
elizaLogger.info("txHash ", txHash);

const pnl = await calculateOverallPNL(
this.runtime,
this.runtime.getSetting("WALLET_PUBLIC_KEY") as `0x${string}`,
1000
);
elizaLogger.info("pnl ", pnl);

// Generate and post tweet
await this.handleTweetPosting(
event,
Expand Down Expand Up @@ -485,22 +479,16 @@ export const calculateOverallPNL = async (
publicKey: `0x${string}`,
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;
};

Expand All @@ -518,21 +506,23 @@ export async function getTotalBalanceUSD(
const ethBalanceBaseUnits = await client.getBalance({
address: publicKey,
});
elizaLogger.info(`ethBalanceBaseUnits ${ethBalanceBaseUnits}`);
const ethBalance = Number(ethBalanceBaseUnits) / 1e18;
elizaLogger.info(`ethBalance ${ethBalance}`);
elizaLogger.info(`ethBalance ${ethBalance}`);
const priceInquiry = await getPriceInquiry(
runtime,
"ETH",
ethBalance,
"USDC",
"base"
);
if (priceInquiry == null) {
elizaLogger.error("priceInquiry is null");
return 0;
}
// get latest quote
elizaLogger.info("Getting quote for swap", JSON.stringify(priceInquiry));
const quote = await getQuoteObj(runtime, priceInquiry, publicKey);
elizaLogger.info("quote ", JSON.stringify(quote));
const ethBalanceUSD = Number(quote.buyAmount) / 1e6;
elizaLogger.info(`ethBalanceUSD ${ethBalanceUSD}`);
const usdcBalanceBaseUnits = await readContractWrapper(
runtime,
"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
Expand All @@ -544,7 +534,6 @@ export async function getTotalBalanceUSD(
erc20Abi
);
const usdcBalance = Number(usdcBalanceBaseUnits) / 1e6;
elizaLogger.info(`usdcBalance ${usdcBalance}`);
return ethBalanceUSD + usdcBalance;
}

Expand Down
17 changes: 6 additions & 11 deletions packages/plugin-0x/src/actions/getIndicativePrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,15 +331,11 @@ export const getPriceInquiry = async (
buyTokenSymbol: string,
chain: string
): Promise<PriceInquiry | null> => {
if (sellAmount < 0.000000000000000001) {
elizaLogger.error(`sellAmount ${sellAmount} is too small`);
return null;
}
try {
// Log input parameters
elizaLogger.info('Getting price inquiry', {
sellTokenSymbol,
sellAmount,
buyTokenSymbol,
chain
});

// Hardcoded chainId for Base network
const chainId = 8453;

Expand Down Expand Up @@ -381,7 +377,7 @@ export const getPriceInquiry = async (
if (!price) return null;

// Handle token approvals
const approved = await handleTokenApprovals(client, price, sellTokenMetadata.address);
const approved = await handleTokenApprovals(client, price, sellTokenMetadata.address as `0x${string}`);
if (!approved) return null;

// Format response
Expand All @@ -406,15 +402,14 @@ export const getPriceInquiry = async (
const getPrice = async (zxClient: any, params: any): Promise<GetIndicativePriceResponse | null> => {
try {
const price = await zxClient.swap.allowanceHolder.getPrice.query(params) as GetIndicativePriceResponse;
elizaLogger.info('Received price quote', price);
return price;
} catch (error) {
elizaLogger.error("Error getting price:", error.message);
return null;
}
};

const handleTokenApprovals = async (client: any, price: GetIndicativePriceResponse, sellTokenAddress: string = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'): Promise<boolean> => {
const handleTokenApprovals = async (client: any, price: GetIndicativePriceResponse, sellTokenAddress: `0x${string}` = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'): Promise<boolean> => {
try {
const sellTokenContract = getContract({
address: sellTokenAddress,
Expand Down
5 changes: 0 additions & 5 deletions packages/plugin-0x/src/actions/swap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,6 @@ export const tokenSwap = async (runtime: IAgentRuntime, quantity: number, fromCu
try {
// get indicative price
priceInquiry = await getPriceInquiry(runtime, fromCurrency, quantity, toCurrency, chain);
elizaLogger.info("priceInquiry ", JSON.stringify(priceInquiry))
} catch (error) {
elizaLogger.error("Error during price inquiry", error.message);
return null;
Expand All @@ -207,9 +206,7 @@ export const tokenSwap = async (runtime: IAgentRuntime, quantity: number, fromCu
let quote = null;
try {
// get latest quote
elizaLogger.info("Getting quote for swap", JSON.stringify(priceInquiry));
quote = await getQuoteObj(runtime, priceInquiry, address);
elizaLogger.info("quotes ", JSON.stringify(quote))
} catch (error) {
elizaLogger.error("Error during quote retrieval", error.message);
return null;
Expand Down Expand Up @@ -248,12 +245,10 @@ export const tokenSwap = async (runtime: IAgentRuntime, quantity: number, fromCu
nonce: nonce,
kzg: undefined,
});
elizaLogger.info("txHash", txHash)
// Wait for transaction confirmation
const receipt = await client.waitForTransactionReceipt({
hash: txHash,
});
elizaLogger.info("receipt ", receipt)
if (receipt.status === "success") {
elizaLogger.info(`✅ Swap executed successfully!\nView on Explorer: ${CHAIN_EXPLORERS[chainId]}/tx/${txHash}`, { hash: txHash, status: "success" });
return txHash;
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-coinbase/src/plugins/advancedTrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,5 +469,5 @@ export const advancedTradePlugin: Plugin = {
name: "advancedTradePlugin",
description: "Enables advanced trading using Coinbase Advanced Trading API",
actions: [executeAdvancedTradeAction],
providers: [tradeProvider],
providers: [],
};
2 changes: 1 addition & 1 deletion packages/plugin-coinbase/src/plugins/massPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,5 +464,5 @@ export const coinbaseMassPaymentsPlugin: Plugin = {
description:
"Processes mass payouts using Coinbase SDK and logs all transactions (success and failure) to a CSV file. Provides dynamic transaction data through a provider.",
actions: [sendMassPayoutAction],
providers: [massPayoutProvider],
providers: [],
};
8 changes: 0 additions & 8 deletions packages/plugin-coinbase/src/plugins/tokenContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,13 +569,6 @@ export const readContractWrapper = async (runtime: IAgentRuntime, contractAddres
runtime.getSetting("COINBASE_PRIVATE_KEY") ??
process.env.COINBASE_PRIVATE_KEY,
});
elizaLogger.info("Reading contract:", {
contractAddress,
method,
args,
networkId,
abi,
});

const result = await readContract({
networkId,
Expand All @@ -585,6 +578,5 @@ export const readContractWrapper = async (runtime: IAgentRuntime, contractAddres
abi,
});
const serializedResult = serializeBigInt(result);
elizaLogger.info("Contract read result:", serializedResult);
return serializedResult;
};
2 changes: 1 addition & 1 deletion packages/plugin-coinbase/src/plugins/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -344,5 +344,5 @@ export const tradePlugin: Plugin = {
name: "tradePlugin",
description: "Enables asset trading using the Coinbase SDK.",
actions: [executeTradeAction],
providers: [tradeProvider],
providers: [],
};
2 changes: 1 addition & 1 deletion packages/plugin-coinbase/src/plugins/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,5 +218,5 @@ export const webhookPlugin: Plugin = {
name: "webhookPlugin",
description: "Manages webhooks using the Coinbase SDK.",
actions: [createWebhookAction],
providers: [webhookProvider],
providers: [],
};
5 changes: 3 additions & 2 deletions packages/plugin-coinbase/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ export async function initializeWallet(
elizaLogger.error("Invalid wallet type provided.");
throw new Error("Invalid wallet type");
}
elizaLogger.log("Importing existing wallet using stored seed and wallet ID:", {
elizaLogger.info("Importing existing wallet using stored seed and wallet ID:", {
seed,
walletId,
walletType,
networkId,
});
if (!seed || seed === '') {
// No stored seed or wallet ID, creating a new wallet
wallet = await Wallet.create({ networkId: "ethereum-mainnet" });
wallet = await Wallet.create({ networkId: networkId});
elizaLogger.log("Created new wallet:", wallet.getId());
// Export wallet data directly
const walletData: WalletData = wallet.export();
Expand Down Expand Up @@ -126,6 +126,7 @@ export async function initializeWallet(
} else {
// Importing existing wallet using stored seed and wallet ID
// Always defaults to base-mainnet we can't select the network here

wallet = await Wallet.import(
seed as unknown as MnemonicSeedPhrase,
networkId,
Expand Down

0 comments on commit f90f78d

Please sign in to comment.