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

feat: get usd based selling working #305

Merged
merged 1 commit into from
Jan 26, 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
20 changes: 9 additions & 11 deletions packages/plugin-coinbase/src/plugins/massPayments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export const massPayoutProvider: Provider = {
transactionHistory: transactions,
};
} catch (error) {
elizaLogger.error("Error in massPayoutProvider:", error);
elizaLogger.error("Error in massPayoutProvider:", error.message);
return { csvRecords: [], balances: [], transactions: [] };
}
},
Expand All @@ -116,7 +116,7 @@ async function executeMassPayout(
elizaLogger.debug("Initializing sending wallet");
sendingWallet = await initializeWallet(runtime, networkId);
} catch (error) {
elizaLogger.error("Error initializing sending wallet:", error);
elizaLogger.error("Error initializing sending wallet:", error.message);
throw error;
}
for (const address of receivingAddresses) {
Expand Down Expand Up @@ -157,16 +157,16 @@ async function executeMassPayout(

transactions.push({
address,
amount: transfer.getAmount().toNumber(),
amount: transfer?.getAmount()?.toNumber(),
status: "Success",
errorCode: null,
transactionUrl: transfer.getTransactionLink(),
transactionUrl: transfer?.getTransactionLink(),
});
} catch (error) {
elizaLogger.error(
"Error during transfer for address:",
address,
error
error.message
);
transactions.push({
address,
Expand Down Expand Up @@ -198,16 +198,15 @@ async function executeMassPayout(
assetId,
charityAddress
);

transactions.push({
address: charityAddress,
amount: charityTransfer.getAmount().toNumber(),
amount: charityTransfer?.getAmount()?.toNumber(),
status: "Success",
errorCode: null,
transactionUrl: charityTransfer.getTransactionLink(),
transactionUrl: charityTransfer?.getTransactionLink(),
});
} catch (error) {
elizaLogger.error("Error during charity transfer:", error);
elizaLogger.error("Error during charity transfer:", error.message);
transactions.push({
address: charityAddress,
amount: transferAmount * 0.01,
Expand Down Expand Up @@ -375,8 +374,7 @@ Details:
${successTransactions.length > 0 ? `✅ Successful Transactions:\n${successDetails}` : "No successful transactions."}
${failedTransactions.length > 0 ? `❌ Failed Transactions:\n${failedDetails}` : "No failed transactions."}
${charityTransactions.length > 0 ? `✅ Charity Transactions:\n${charityDetails}` : "No charity transactions."}

Check the CSV file for full details.`,
`,
},
[]
);
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-coinbase/src/plugins/tokenContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ export const tokenContractPlugin: Plugin = {
"Enables deployment, invocation, and reading of ERC20, ERC721, and ERC1155 token contracts using the Coinbase SDK",
actions: [
deployTokenContractAction,
invokeContractAction,
// invokeContractAction,
readContractAction,
],
};
63 changes: 46 additions & 17 deletions packages/plugin-coinbase/src/plugins/trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,42 @@ import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import { createArrayCsvWriter } from "csv-writer";
import { RESTClient } from "../../advanced-sdk-ts/src/rest";

// Dynamically resolve the file path to the src/plugins directory
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const baseDir = path.resolve(__dirname, "../../plugin-coinbase/src/plugins");
const tradeCsvFilePath = path.join(baseDir, "trades.csv");

// async function getPrice(ticker: string) {
// elizaLogger.debug("Fetching product info for productId:", productId);
// try {
// const productInfo = await client.getProduct({productId});
// const price = JSON.parse(productInfo)?.price;
// elizaLogger.info("Product info retrieved:", productInfo);
// elizaLogger.info("Price:", price);
// return Number(price);
// } catch (error) {
// elizaLogger.error("Error fetching product info:", error);
// return null;
// }
// }
async function getPrice(runtime: IAgentRuntime, ticker: string) {
Coinbase.configure({
apiKeyName:
runtime.getSetting("COINBASE_API_KEY") ??
process.env.COINBASE_API_KEY,
privateKey:
runtime.getSetting("COINBASE_PRIVATE_KEY") ??
process.env.COINBASE_PRIVATE_KEY,
});
const productId = `${ticker.toUpperCase()}-USD`;
const client = new RESTClient(
runtime.getSetting("COINBASE_API_KEY") ??
process.env.COINBASE_API_KEY,
runtime.getSetting("COINBASE_PRIVATE_KEY") ??
process.env.COINBASE_PRIVATE_KEY
);
elizaLogger.debug("Fetching product info for productId:", productId);
try {
const productInfo = await client.getProduct({productId});
const price = JSON.parse(productInfo)?.price;
elizaLogger.info("Product info retrieved:", productInfo);
elizaLogger.info("Price:", price);
return Number(price);
} catch (error) {
elizaLogger.error("Error fetching product info:", error);
return null;
}
}

export const tradeProvider: Provider = {
get: async (runtime: IAgentRuntime, _message: Memory) => {
Expand Down Expand Up @@ -164,9 +180,9 @@ export const executeTradeAction: Action = {
return;
}

const { network, amount, sourceAsset, targetAsset } =
const { network, amount, sourceAsset, targetAsset, side } =
tradeDetails.object as TradeContent;

elizaLogger.info("Trade details:", JSON.stringify(tradeDetails.object));
const allowedNetworks = ["base", "sol", "eth", "arb", "pol"];
if (!allowedNetworks.includes(network)) {
callback(
Expand All @@ -179,22 +195,35 @@ export const executeTradeAction: Action = {
);
return;
}
let amountInCurrency = amount
try {
if (side === "SELL") {
const priceInUSD = await getPrice(runtime, sourceAsset);
await new Promise(resolve => setTimeout(resolve, 5000));
elizaLogger.info("PriceInUSD:", priceInUSD);
amountInCurrency = parseFloat(((1 / priceInUSD) * amountInCurrency).toFixed(7));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't run it on my machine but are we sure about this equation? I'd rather say
amountInCurrency = parseFloat((priceInUSD * amountInCurrency).toFixed(7));

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are sure as I have transfered and it worked as expected got $0.10 worth of ETH etc

elizaLogger.info("Amount in currency:", amountInCurrency);
}
} catch (error) {
elizaLogger.error("Error fetching price:", error.message);
}

const { trade, transfer } = await executeTradeAndCharityTransfer(
runtime,
network,
amount,
amountInCurrency,
sourceAsset,
targetAsset
);
await new Promise(resolve => setTimeout(resolve, 5000));
elizaLogger.info("Trade executed successfully:", JSON.stringify(trade));
elizaLogger.info("Transfer executed successfully:", JSON.stringify(transfer));
let responseText = `Trade executed successfully:
- Network: ${network}
- Amount: ${trade.getFromAmount()}
- From: ${sourceAsset}
- To: ${targetAsset}
- Transaction URL: ${trade.getApproveTransaction().getTransactionLink() || ""}
- Transaction URL: ${trade.getApproveTransaction()?.getTransactionLink() || trade.getTransaction()?.getTransactionLink() || ""}
- Charity Transaction URL: ${transfer?.getTransactionLink() || "N/A"}`;

if (transfer) {
Expand Down
12 changes: 6 additions & 6 deletions packages/plugin-coinbase/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ export async function executeTransferAndCharityTransfer(
const assetIdLowercase = sourceAsset.toLowerCase();

let charityTransfer: Transfer;
if (charityAddress && charityAmount > 0) {
if (false) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

disable for now

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is that? If we want to keep that code for later refactor, let's leave TODO comment

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When transfers are too small it fails so removing for now will add it back in this weekend don't worry :)

charityTransfer = await executeTransfer(
wallet,
charityAmount,
Expand All @@ -448,17 +448,17 @@ export async function executeTransferAndCharityTransfer(
await transfer.wait();

let responseText = `Transfer executed successfully:
- Amount: ${transfer.getAmount()}
- Amount: ${transfer?.getAmount()}
- Asset: ${assetIdLowercase}
- Destination: ${targetAddress}
- Transaction URL: ${transfer.getTransactionLink() || ""}`;
- Transaction URL: ${transfer?.getTransactionLink() || ""}`;

if (charityTransfer) {
responseText += `
- Charity Amount: ${charityTransfer.getAmount()}
- Charity Transaction URL: ${charityTransfer.getTransactionLink() || ""}`;
- Charity Amount: ${charityTransfer?.getAmount()}
- Charity Transaction URL: ${charityTransfer?.getTransactionLink() || ""}`;
} else {
responseText += "\n(Note: Charity transfer was not completed)";
responseText += "\nNote: Charity transfer was not completed";
}

elizaLogger.log(responseText);
Expand Down
Loading