@theschein/plugin-polymarket
Version:
ElizaOS plugin for Polymarket prediction markets
163 lines (156 loc) • 5.96 kB
JavaScript
// src/utils/depositManager.ts
import { logger } from "@elizaos/core";
import { ethers } from "ethers";
import { getProxyWalletAddress } from "@polymarket/sdk";
var PROXY_WALLET_FACTORIES = {
// For MetaMask users (Gnosis Safe factory)
GNOSIS_SAFE_FACTORY: "0xaacfeea03eb1561c4e67d661e40682bd20e3541b",
// For MagicLink users (Polymarket proxy factory)
POLYMARKET_PROXY_FACTORY: "0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"
};
var USDC_CONTRACT_ADDRESS = "0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174";
var ERC20_ABI = [
"function transfer(address to, uint256 amount) returns (bool)",
"function balanceOf(address owner) view returns (uint256)",
"function decimals() view returns (uint8)",
"function approve(address spender, uint256 amount) returns (bool)",
"function allowance(address owner, address spender) view returns (uint256)"
];
async function getDepositAddress(runtime) {
logger.info("[depositManager] Getting Polymarket deposit address");
try {
const privateKey = runtime.getSetting("WALLET_PRIVATE_KEY") || runtime.getSetting("PRIVATE_KEY") || runtime.getSetting("POLYMARKET_PRIVATE_KEY");
if (!privateKey) {
throw new Error("No private key found for deposit address calculation");
}
const formattedPrivateKey = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
const wallet = new ethers.Wallet(formattedPrivateKey);
const userAddress = wallet.address;
const proxyAddress = getProxyWalletAddress(
PROXY_WALLET_FACTORIES.GNOSIS_SAFE_FACTORY,
userAddress
);
logger.info(`[depositManager] Calculated proxy wallet address:`, {
userAddress,
proxyAddress,
factory: "GNOSIS_SAFE_FACTORY"
});
return proxyAddress;
} catch (error) {
logger.error(`[depositManager] Error calculating deposit address: ${error}`);
throw new Error(
`Failed to calculate deposit address: ${error instanceof Error ? error.message : "Unknown error"}`
);
}
}
async function depositUSDC(runtime, amount) {
logger.info(`[depositManager] Initiating USDC deposit of $${amount}`);
try {
const privateKey = runtime.getSetting("WALLET_PRIVATE_KEY") || runtime.getSetting("PRIVATE_KEY") || runtime.getSetting("POLYMARKET_PRIVATE_KEY");
if (!privateKey) {
throw new Error("No private key found for deposit transaction");
}
const formattedPrivateKey = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
const rpcProviders = [
"https://polygon-rpc.com",
"https://rpc-mainnet.matic.network",
"https://rpc-mainnet.maticvigil.com"
];
let provider = null;
for (const rpcUrl of rpcProviders) {
try {
const testProvider = new ethers.JsonRpcProvider(rpcUrl);
await testProvider.getBlockNumber();
provider = testProvider;
logger.info(`[depositManager] Connected to RPC: ${rpcUrl}`);
break;
} catch (error) {
logger.warn(`[depositManager] RPC provider ${rpcUrl} failed`);
continue;
}
}
if (!provider) {
throw new Error("All RPC providers failed");
}
const wallet = new ethers.Wallet(formattedPrivateKey, provider);
const userAddress = wallet.address;
const proxyWalletAddress = await getDepositAddress(runtime);
const usdcContract = new ethers.Contract(
USDC_CONTRACT_ADDRESS,
ERC20_ABI,
wallet
);
const balanceRaw = await usdcContract.balanceOf(userAddress);
const decimals = await usdcContract.decimals();
const currentBalance = ethers.formatUnits(balanceRaw, decimals);
const depositAmountWei = ethers.parseUnits(amount, decimals);
if (balanceRaw < depositAmountWei) {
throw new Error(
`Insufficient USDC balance. Have: $${currentBalance}, Need: $${amount}`
);
}
logger.info(`[depositManager] Executing USDC transfer:`, {
from: userAddress,
to: proxyWalletAddress,
amount: `$${amount}`,
balance: `$${currentBalance}`
});
const transferTx = await usdcContract.transfer(
proxyWalletAddress,
depositAmountWei
);
logger.info(`[depositManager] Transfer transaction submitted: ${transferTx.hash}`);
const receipt = await transferTx.wait();
if (receipt?.status === 1) {
logger.info(`[depositManager] Deposit successful! Block: ${receipt.blockNumber}`);
return {
userAddress,
proxyWalletAddress,
depositAmount: amount,
userBalance: currentBalance,
transactionHash: transferTx.hash,
success: true
};
} else {
throw new Error("Transaction failed");
}
} catch (error) {
logger.error(`[depositManager] Deposit failed: ${error}`);
return {
userAddress: "",
proxyWalletAddress: "",
depositAmount: amount,
userBalance: "0",
success: false
};
}
}
function formatDepositInfo(depositInfo) {
if (depositInfo.success) {
return `\u2705 **USDC Deposit Successful**
**Transaction Details:**
\u2022 **Amount Deposited**: $${depositInfo.depositAmount}
\u2022 **From**: ${depositInfo.userAddress}
\u2022 **To**: ${depositInfo.proxyWalletAddress}
\u2022 **Transaction**: ${depositInfo.transactionHash}
\u2022 **Remaining Wallet Balance**: $${(parseFloat(depositInfo.userBalance) - parseFloat(depositInfo.depositAmount)).toFixed(2)}
\u{1F389} **Funds Available for Trading**
Your USDC has been deposited to your Polymarket account and is now available for trading!
*You can now place orders on prediction markets.*`;
} else {
return `\u274C **USDC Deposit Failed**
**Attempted Deposit:**
\u2022 **Amount**: $${depositInfo.depositAmount}
**Common Issues:**
\u2022 Insufficient USDC balance in wallet
\u2022 Network connectivity problems
\u2022 Transaction rejected or failed
Please check your wallet balance and try again.`;
}
}
export {
getDepositAddress,
depositUSDC,
formatDepositInfo
};
//# sourceMappingURL=chunk-DFK6DJJV.js.map