Skip to content

Commit

Permalink
Merge pull request #305 from Sifchain/cleanup4
Browse files Browse the repository at this point in the history
feat: get usd based selling working
  • Loading branch information
monilpat authored Jan 26, 2025
2 parents fb35ef3 + 210e910 commit bd6fe08
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 35 deletions.
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));
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) {
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

0 comments on commit bd6fe08

Please sign in to comment.