Skip to content

Commit

Permalink
Merge pull request elizaOS#1429 from alessandromazza98/1194-improve-l…
Browse files Browse the repository at this point in the history
…ogging-in-plugins-coinbase

improve logging in plugin-coinbase
  • Loading branch information
monilpat authored Dec 24, 2024
2 parents b3f24b8 + b4a4442 commit e9a139d
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 53 deletions.
7 changes: 7 additions & 0 deletions packages/plugin-coinbase/src/plugins/advancedTrade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ const tradeCsvFilePath = path.join(baseDir, "advanced_trades.csv");

const tradeProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
elizaLogger.debug("Starting tradeProvider function");
try {
const client = new RESTClient(
runtime.getSetting("COINBASE_API_KEY") ??
Expand Down Expand Up @@ -103,6 +104,7 @@ const tradeProvider: Provider = {
};

export async function appendTradeToCsv(tradeResult: any) {
elizaLogger.debug("Starting appendTradeToCsv function");
try {
const csvWriter = createArrayCsvWriter({
path: tradeCsvFilePath,
Expand Down Expand Up @@ -139,6 +141,7 @@ async function hasEnoughBalance(
amount: number,
side: string
): Promise<boolean> {
elizaLogger.debug("Starting hasEnoughBalance function");
try {
const response = await client.listAccounts({});
const accounts = JSON.parse(response);
Expand Down Expand Up @@ -216,6 +219,7 @@ export const executeAdvancedTradeAction: Action = {
let client: RESTClient;

// Initialize client
elizaLogger.debug("Starting advanced trade client initialization");
try {
client = new RESTClient(
runtime.getSetting("COINBASE_API_KEY") ??
Expand All @@ -237,6 +241,7 @@ export const executeAdvancedTradeAction: Action = {

// Generate trade details
let tradeDetails;
elizaLogger.debug("Starting trade details generation");
try {
tradeDetails = await generateObject({
runtime,
Expand Down Expand Up @@ -276,6 +281,7 @@ export const executeAdvancedTradeAction: Action = {

// Configure order
let orderConfiguration: OrderConfiguration;
elizaLogger.debug("Starting order configuration");
try {
if (orderType === "MARKET") {
orderConfiguration =
Expand Down Expand Up @@ -323,6 +329,7 @@ export const executeAdvancedTradeAction: Action = {
// Execute trade
let order: CreateOrderResponse;
try {
elizaLogger.debug("Executing the trade");
if (
!(await hasEnoughBalance(
client,
Expand Down
32 changes: 18 additions & 14 deletions packages/plugin-coinbase/src/plugins/commerce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ interface ChargeRequest {
}

export async function createCharge(apiKey: string, params: ChargeRequest) {
elizaLogger.debug("Starting createCharge function");
try {
const response = await fetch(url, {
method: "POST",
Expand All @@ -47,13 +48,14 @@ export async function createCharge(apiKey: string, params: ChargeRequest) {
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error creating charge:", error);
elizaLogger.error("Error creating charge:", error);
throw error;
}
}

// Function to fetch all charges
export async function getAllCharges(apiKey: string) {
elizaLogger.debug("Starting getAllCharges function");
try {
const response = await fetch(url, {
method: "GET",
Expand All @@ -72,13 +74,14 @@ export async function getAllCharges(apiKey: string) {
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error fetching charges:", error);
elizaLogger.error("Error fetching charges:", error);
throw error;
}
}

// Function to fetch details of a specific charge
export async function getChargeDetails(apiKey: string, chargeId: string) {
elizaLogger.debug("Starting getChargeDetails function");
const getUrl = `${url}${chargeId}`;

try {
Expand All @@ -99,7 +102,7 @@ export async function getChargeDetails(apiKey: string, chargeId: string) {
const data = await response.json();
return data;
} catch (error) {
console.error(
elizaLogger.error(
`Error fetching charge details for ID ${chargeId}:`,
error
);
Expand Down Expand Up @@ -140,7 +143,7 @@ export const createCoinbaseChargeAction: Action = {
_options: any,
callback: HandlerCallback
) => {
elizaLogger.log("Composing state for message:", message);
elizaLogger.info("Composing state for message:", message);
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
Expand Down Expand Up @@ -172,10 +175,10 @@ export const createCoinbaseChargeAction: Action = {
return;
}

elizaLogger.log("Charge details received:", chargeDetails);
elizaLogger.info("Charge details received:", chargeDetails);

// Initialize Coinbase Commerce client

elizaLogger.debug("Starting Coinbase Commerce client initialization");
try {
// Create a charge
const chargeResponse = await createCharge(
Expand All @@ -191,7 +194,7 @@ export const createCoinbaseChargeAction: Action = {
}
);

elizaLogger.log(
elizaLogger.info(
"Coinbase Commerce charge created:",
chargeResponse
);
Expand Down Expand Up @@ -333,7 +336,7 @@ export const getAllChargesAction: Action = {
callback: HandlerCallback
) => {
try {
elizaLogger.log("Composing state for message:", message);
elizaLogger.info("Composing state for message:", message);
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
Expand All @@ -343,7 +346,7 @@ export const getAllChargesAction: Action = {
runtime.getSetting("COINBASE_COMMERCE_KEY")
);

elizaLogger.log("Fetched all charges:", charges);
elizaLogger.info("Fetched all charges:", charges);

callback(
{
Expand Down Expand Up @@ -397,7 +400,7 @@ export const getChargeDetailsAction: Action = {
_options: any,
callback: HandlerCallback
) => {
elizaLogger.log("Composing state for message:", message);
elizaLogger.info("Composing state for message:", message);
if (!state) {
state = (await runtime.composeState(message)) as State;
} else {
Expand Down Expand Up @@ -434,7 +437,7 @@ export const getChargeDetailsAction: Action = {
charge.id
);

elizaLogger.log("Fetched charge details:", chargeDetails);
elizaLogger.info("Fetched charge details:", chargeDetails);

callback(
{
Expand Down Expand Up @@ -486,6 +489,7 @@ export const getChargeDetailsAction: Action = {

export const chargeProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
elizaLogger.debug("Starting chargeProvider.get function");
const charges = await getAllCharges(
runtime.getSetting("COINBASE_COMMERCE_KEY")
);
Expand All @@ -504,16 +508,16 @@ export const chargeProvider: Provider = {
privateKey: coinbasePrivateKey,
});
const { balances, transactions } = await getWalletDetails(runtime);
elizaLogger.log("Current Balances:", balances);
elizaLogger.log("Last Transactions:", transactions);
elizaLogger.info("Current Balances:", balances);
elizaLogger.info("Last Transactions:", transactions);
}
const formattedCharges = charges.map((charge) => ({
id: charge.id,
name: charge.name,
description: charge.description,
pricing: charge.pricing,
}));
elizaLogger.log("Charges:", formattedCharges);
elizaLogger.info("Charges:", formattedCharges);
return { charges: formattedCharges, balances, transactions };
},
};
Expand Down
30 changes: 17 additions & 13 deletions packages/plugin-coinbase/src/plugins/massPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const csvFilePath = path.join(baseDir, "transactions.csv");

export const massPayoutProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
elizaLogger.debug("Starting massPayoutProvider.get function");
try {
Coinbase.configure({
apiKeyName:
Expand All @@ -50,7 +51,7 @@ export const massPayoutProvider: Provider = {
runtime.getSetting("COINBASE_PRIVATE_KEY") ??
process.env.COINBASE_PRIVATE_KEY,
});
elizaLogger.log("Reading CSV file from:", csvFilePath);
elizaLogger.info("Reading CSV file from:", csvFilePath);

// Ensure the CSV file exists
if (!fs.existsSync(csvFilePath)) {
Expand All @@ -66,7 +67,7 @@ export const massPayoutProvider: Provider = {
],
});
await csvWriter.writeRecords([]); // Create an empty file with headers
elizaLogger.log("New CSV file created with headers.");
elizaLogger.info("New CSV file created with headers.");
}

// Read and parse the CSV file
Expand All @@ -78,9 +79,9 @@ export const massPayoutProvider: Provider = {

const { balances, transactions } = await getWalletDetails(runtime);

elizaLogger.log("Parsed CSV records:", records);
elizaLogger.log("Current Balances:", balances);
elizaLogger.log("Last Transactions:", transactions);
elizaLogger.info("Parsed CSV records:", records);
elizaLogger.info("Current Balances:", balances);
elizaLogger.info("Last Transactions:", transactions);

return {
currentTransactions: records.map((record: any) => ({
Expand All @@ -107,25 +108,27 @@ async function executeMassPayout(
transferAmount: number,
assetId: string
): Promise<Transaction[]> {
elizaLogger.debug("Starting executeMassPayout function");
const transactions: Transaction[] = [];
const assetIdLowercase = assetId.toLowerCase();
let sendingWallet: Wallet;
try {
elizaLogger.debug("Initializing sending wallet");
sendingWallet = await initializeWallet(runtime, networkId);
} catch (error) {
elizaLogger.error("Error initializing sending wallet:", error);
throw error;
}
for (const address of receivingAddresses) {
elizaLogger.log("Processing payout for address:", address);
elizaLogger.info("Processing payout for address:", address);
if (address) {
try {
// Check balance before initiating transfer

const walletBalance =
await sendingWallet.getBalance(assetIdLowercase);

elizaLogger.log("Wallet balance for asset:", {
elizaLogger.info("Wallet balance for asset:", {
assetId,
walletBalance,
});
Expand Down Expand Up @@ -174,7 +177,7 @@ async function executeMassPayout(
});
}
} else {
elizaLogger.log("Skipping invalid or empty address.");
elizaLogger.info("Skipping invalid or empty address.");
transactions.push({
address: "Invalid or Empty",
amount: transferAmount,
Expand All @@ -188,6 +191,7 @@ async function executeMassPayout(
const charityAddress = getCharityAddress(networkId);

try {
elizaLogger.debug("Sending 1% to charity:", charityAddress);
const charityTransfer = await executeTransfer(
sendingWallet,
transferAmount * 0.01,
Expand All @@ -213,7 +217,7 @@ async function executeMassPayout(
});
}
await appendTransactionsToCsv(transactions);
elizaLogger.log("Finished processing mass payouts.");
elizaLogger.info("Finished processing mass payouts.");
return transactions;
}

Expand All @@ -224,7 +228,7 @@ export const sendMassPayoutAction: Action = {
description:
"Sends mass payouts to a list of receiving addresses using a predefined sending wallet and logs all transactions to a CSV file.",
validate: async (runtime: IAgentRuntime, _message: Memory) => {
elizaLogger.log("Validating runtime and message...");
elizaLogger.info("Validating runtime and message...");
return (
!!(
runtime.character.settings.secrets?.COINBASE_API_KEY ||
Expand All @@ -243,7 +247,7 @@ export const sendMassPayoutAction: Action = {
_options: any,
callback: HandlerCallback
) => {
elizaLogger.log("Starting SEND_MASS_PAYOUT handler...");
elizaLogger.debug("Starting SEND_MASS_PAYOUT handler...");
try {
Coinbase.configure({
apiKeyName:
Expand Down Expand Up @@ -273,7 +277,7 @@ export const sendMassPayoutAction: Action = {
schema: TransferSchema,
});

elizaLogger.log(
elizaLogger.info(
"Transfer details generated:",
transferDetails.object
);
Expand Down Expand Up @@ -319,7 +323,7 @@ export const sendMassPayoutAction: Action = {
return;
}

elizaLogger.log("◎ Starting mass payout...");
elizaLogger.info("◎ Starting mass payout...");
const transactions = await executeMassPayout(
runtime,
network,
Expand Down
Loading

0 comments on commit e9a139d

Please sign in to comment.