Files
web/scripts/create_pool_from_prices.js

476 lines
16 KiB
JavaScript

#!/usr/bin/env node
/**
* Create Pool from Real-Time Prices Script
* Fetches real-time prices from CoinGecko and creates a new pool on the chain specified (could be mockchain, sepolia or prod)
*/
import { ethers } from 'ethers';
import { readFile } from 'fs/promises';
import { config } from 'dotenv';
// Load environment variables from .env-secret
config({ path: new URL('../.env-secret', import.meta.url).pathname });
// ============================================================================
// CONFIGURATION
// ============================================================================
// Network flag: 'mockchain' or 'mainnet'
const NETWORK = process.env.NETWORK || 'mainnet';
// Network-specific configuration
const NETWORK_CONFIG = {
mockchain: {
rpcUrl: 'http://localhost:8545',
privateKey: '0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', // Dev wallet #4 (sender)
receiverPrivateKey: '0x4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356', // Receiver wallet
receiverAddress: '0x14dC79964da2C08b23698B3D3cc7Ca32193d9955', // Receiver public key
chainId: '31337',
tokens: {
USDT: {
address: '0xbdEd0D2bf404bdcBa897a74E6657f1f12e5C6fb6', // USXD on mockchain
coingeckoId: 'tether',
decimals: 6,
feePpm: 400
},
USDC: {
address: '0x2910E325cf29dd912E3476B61ef12F49cb931096', // FUSD on mockchain
coingeckoId: 'usd-coin',
decimals: 6,
feePpm: 400
}
}
},
mainnet: {
rpcUrl: process.env.MAINNET_RPC_URL,
privateKey: process.env.PRIVATE_KEY,
receiverAddress: '0xd3b310bd32d782f89eea49cb79656bcaccde7213', // Same as payer for mainnet
chainId: '1',
tokens: {
USDT: {
address: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
coingeckoId: 'tether',
decimals: 6,
feePpm: 40 // 0.0004%
},
USDC: {
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
coingeckoId: 'usd-coin',
decimals: 6,
feePpm: 40 // 0.0004%
},
WBTC: {
address: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',
coingeckoId: 'wrapped-bitcoin',
decimals: 8,
feePpm: 300 // 0.00030%
},
WETH: {
address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
coingeckoId: 'weth',
decimals: 18,
feePpm: 350 // 0.0035%
},
UNI: {
address: '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984',
coingeckoId: 'uniswap',
decimals: 18,
feePpm: 1450 // 0.00145%
},
WSOL: {
address: '0xD31a59c85aE9D8edEFeC411D448f90841571b89c', // Wormhole Wrapped SOL
coingeckoId: 'solana',
decimals: 9,
feePpm: 950 // 0.00095%
},
TRX: {
address: '0x50327c6c5a14DCaDE707ABad2E27eB517df87AB5',
coingeckoId: 'tron',
decimals: 6,
feePpm: 950 // 0.00095%
},
AAVE: {
address: '0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9',
coingeckoId: 'aave',
decimals: 18,
feePpm: 1450 // 0.00145%
},
PEPE: {
address: '0x6982508145454Ce325dDbE47a25d4ec3d2311933',
coingeckoId: 'pepe',
decimals: 18,
feePpm: 2150 // 0.00215%
},
SHIB: {
address: '0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE',
coingeckoId: 'shiba-inu',
decimals: 18,
feePpm: 2150 // 0.00215%
}
}
}
};
// Get current network config
const currentConfig = NETWORK_CONFIG[NETWORK];
if (!currentConfig) {
console.error(`[!] Invalid NETWORK: ${NETWORK}. Must be 'mockchain' or 'mainnet'`);
process.exit(1);
}
const RPC_URL = currentConfig.rpcUrl;
const PRIVATE_KEY = currentConfig.privateKey;
const RECEIVER_ADDRESS = currentConfig.receiverAddress || process.env.RECEIVER_ADDRESS;
// Validate required config for mainnet
if (NETWORK === 'mainnet' && (!RPC_URL || !PRIVATE_KEY)) {
console.error('[!] Missing required environment variables for mainnet');
console.error(' Required: MAINNET_RPC_URL, PRIVATE_KEY');
process.exit(1);
}
if (!RECEIVER_ADDRESS) {
console.error('[!] Missing RECEIVER_ADDRESS in .env-secret file');
process.exit(1);
}
// Use network-specific tokens
const TEST_TOKENS = currentConfig.tokens;
// Default pool parameters
const DEFAULT_POOL_PARAMS = {
name: 'Original Genesis of Liquidity Party',
symbol: 'OG.LP',
kappa: ethers.BigNumber.from('184467440737095520'), //0.01 * 2^64
swapFeesPpm: Object.values(TEST_TOKENS).map(t => t.feePpm),
flashFeePpm: 5, // 0.0005%
stable: false,
initialLpAmount: ethers.utils.parseUnits('1', 18) // 100 USD in 18 decimals
};
// Input amount in USD
const INPUT_USD_AMOUNT = 1;
// ============================================================================
// LOAD ABIs AND CONFIG
// ============================================================================
const chainInfoData = JSON.parse(await readFile(new URL('../src/contracts/liqp-deployments.json', import.meta.url), 'utf-8'));
const PARTY_PLANNER_ADDRESS = chainInfoData[currentConfig.chainId].v1.PartyPlanner;
const ERC20ABI = [
{ "type": "function", "name": "balanceOf", "stateMutability": "view", "inputs": [{ "name": "account", "type": "address" }], "outputs": [{ "name": "", "type": "uint256" }] },
{ "type": "function", "name": "decimals", "stateMutability": "view", "inputs": [], "outputs": [{ "name": "", "type": "uint8" }] },
{ "type": "function", "name": "approve", "stateMutability": "nonpayable", "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "outputs": [{ "name": "", "type": "bool" }] }
];
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/**
* Fetch real-time prices from CoinGecko API
*/
async function fetchCoinGeckoPrices() {
try {
const ids = Object.values(TEST_TOKENS).map(t => t.coingeckoId).join(',');
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`;
console.log(`[~] Fetching prices from CoinGecko...`);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`CoinGecko API request failed: ${response.statusText}`);
}
const data = await response.json();
const prices = {};
for (const [symbol, tokenInfo] of Object.entries(TEST_TOKENS)) {
prices[symbol] = data[tokenInfo.coingeckoId]?.usd || 0;
if (prices[symbol] === 0) {
throw new Error(`Failed to fetch valid price for ${symbol}`);
}
}
console.log(`[+] Prices fetched successfully:`);
for (const [symbol, price] of Object.entries(prices)) {
console.log(` ${symbol.padEnd(6)}: $${price.toLocaleString()}`);
}
return prices;
} catch (error) {
console.error(`[!] Error fetching prices:`, error.message);
throw error;
}
}
/**
* Calculate token amounts based on equal USD distribution
*/
function calculateTokenAmounts(prices, usdAmount) {
const tokenCount = Object.keys(TEST_TOKENS).length;
const usdPerToken = usdAmount / tokenCount; // Equally distribute among all tokens
const tokenAmounts = {};
console.log(`\n[~] Calculated token amounts for $${usdAmount} ($${usdPerToken.toFixed(2)} per token):`);
for (const [symbol, tokenInfo] of Object.entries(TEST_TOKENS)) {
// Calculate raw amount
const rawAmount = usdPerToken / prices[symbol];
// Convert to BigNumber with proper decimals
const amountBN = ethers.utils.parseUnits(rawAmount.toFixed(tokenInfo.decimals), tokenInfo.decimals);
tokenAmounts[symbol] = amountBN;
console.log(` ${symbol.padEnd(6)}: ${rawAmount.toFixed(tokenInfo.decimals)} (${amountBN.toString()} wei)`);
}
return tokenAmounts;
}
/**
* Check token balances
*/
async function checkBalances(provider, wallet, tokenAmounts, receiverAddress) {
console.log(`\n[~] Checking token balances for receiver wallet: ${receiverAddress}`);
const balances = {};
let hasEnoughBalance = true;
for (const [symbol, tokenInfo] of Object.entries(TEST_TOKENS)) {
const tokenContract = new ethers.Contract(tokenInfo.address, ERC20ABI, provider);
const balance = await tokenContract.balanceOf(receiverAddress);
const requiredAmount = tokenAmounts[symbol];
balances[symbol] = balance;
const balanceFormatted = ethers.utils.formatUnits(balance, tokenInfo.decimals);
const requiredFormatted = ethers.utils.formatUnits(requiredAmount, tokenInfo.decimals);
const sufficient = balance.gte(requiredAmount);
console.log(` ${symbol}: ${balanceFormatted} (required: ${requiredFormatted}) ${sufficient ? '✓' : '✗'}`);
if (!sufficient) {
hasEnoughBalance = false;
}
}
if (!hasEnoughBalance) {
console.log(`\n[!] Insufficient token balance. Please ensure receiver wallet has enough tokens.`);
throw new Error('Insufficient token balance');
}
console.log(`[+] All balances sufficient`);
return balances;
}
/**
* Approve tokens for the PartyPlanner contract
*/
async function approveTokens(provider, tokenAmounts, receiverPrivateKey) {
console.log(`\n[~] Approving tokens for PartyPlanner contract...`);
// Connect with receiver wallet for approvals
const receiverWallet = new ethers.Wallet(receiverPrivateKey, provider);
console.log(`[~] Using receiver wallet for approvals: ${receiverWallet.address}`);
for (const [symbol, tokenInfo] of Object.entries(TEST_TOKENS)) {
const tokenContract = new ethers.Contract(tokenInfo.address, ERC20ABI, receiverWallet);
// Approve 1% more than needed to account for fees/slippage
const requiredAmount = tokenAmounts[symbol];
const approvalAmount = requiredAmount.mul(101).div(100); // 1% buffer
console.log(` [~] Approving ${symbol} ${tokenInfo.address} ${approvalAmount} (1% buffer)...`);
try {
// USDT and some tokens require setting allowance to 0 before setting a new value
// Skip for BNB as it has a broken approve function
if (symbol == 'USDT') {
const resetTx = await tokenContract.approve(PARTY_PLANNER_ADDRESS, 0);
await resetTx.wait();
console.log(` [+] ${symbol} allowance reset to 0`);
}
const tx = await tokenContract.approve(PARTY_PLANNER_ADDRESS, approvalAmount);
await tx.wait();
console.log(` [+] ${symbol} approved (tx: ${tx.hash})`);
} catch (error) {
console.error(` [!] Failed to approve ${symbol}:`, error.message);
throw error;
}
}
console.log(`[+] All tokens approved`);
}
/**
* Create a new pool using cast send
*/
async function createPool(wallet, tokenAmounts) {
console.log(`\n[~] Creating new pool...`);
// Prepare parameters
const tokenAddresses = Object.values(TEST_TOKENS).map(t => t.address);
const initialDeposits = Object.keys(TEST_TOKENS).map(symbol => tokenAmounts[symbol].toString());
// Set deadline to 5 minutes from now
const deadline = Math.floor(Date.now() / 1000) + 300;
console.log(`[~] Pool parameters:`);
console.log(` Name: ${DEFAULT_POOL_PARAMS.name}`);
console.log(` Symbol: ${DEFAULT_POOL_PARAMS.symbol}`);
console.log(` Tokens: ${tokenAddresses.join(', ')}`);
console.log(` Swap Fees PPM: [${DEFAULT_POOL_PARAMS.swapFeesPpm.join(', ')}]`);
console.log(` Payer (provides tokens): ${RECEIVER_ADDRESS}`);
console.log(` Receiver (gets LP tokens): ${wallet.address}`);
console.log(` Deadline: ${new Date(deadline * 1000).toISOString()}`);
// Build cast send command
const castCommand = `cast send ${PARTY_PLANNER_ADDRESS} \
"newPool(string,string,address[],int128,uint256[],uint256,bool,address,address,uint256[],uint256,uint256)" \
"${DEFAULT_POOL_PARAMS.name}" \
"${DEFAULT_POOL_PARAMS.symbol}" \
"[${tokenAddresses.join(',')}]" \
${DEFAULT_POOL_PARAMS.kappa.toString()} \
"[${DEFAULT_POOL_PARAMS.swapFeesPpm.join(',')}]" \
${DEFAULT_POOL_PARAMS.flashFeePpm} \
${DEFAULT_POOL_PARAMS.stable} \
${RECEIVER_ADDRESS} \
${wallet.address} \
"[${initialDeposits.join(',')}]" \
${DEFAULT_POOL_PARAMS.initialLpAmount.toString()} \
${deadline} \
--rpc-url '${RPC_URL}' \
--from 0x12db90820dafed100e40e21128e40dcd4ff6b331 \
--trezor --mnemonic-index 0`
console.log(`\n[~] Cast command:\n${castCommand}\n`);
try {
// Execute cast command
const { execSync } = await import('child_process');
const output = execSync(castCommand, { encoding: 'utf-8' });
console.log(`[+] Pool created successfully!`);
console.log(output);
return output;
} catch (error) {
console.error(`[!] Failed to create pool:`, error.message);
if (error.stderr) {
console.error(` Error output: ${error.stderr.toString()}`);
}
throw error;
}
}
/**
* Print help message
*/
function printHelp() {
console.log(`
Usage: node create_pool_from_prices.js [OPTIONS]
Options:
--amount <usd> USD amount to distribute (default: ${INPUT_USD_AMOUNT})
--name <name> Pool name (default: "${DEFAULT_POOL_PARAMS.name}")
--symbol <symbol> Pool symbol (default: "${DEFAULT_POOL_PARAMS.symbol}")
--help, -h Show this help message
Example:
node create_pool_from_prices.js
node create_pool_from_prices.js --amount 200 --name "My Pool" --symbol "MP"
`);
}
// ============================================================================
// MAIN FUNCTION
// ============================================================================
async function main() {
console.log(`${'='.repeat(70)}`);
console.log(`Create Pool from Real-Time Prices`);
console.log(`Network: ${NETWORK}`);
console.log(`${'='.repeat(70)}\n`);
// Parse command line arguments
const args = process.argv.slice(2);
if (args.includes('--help') || args.includes('-h')) {
printHelp();
process.exit(0);
}
let usdAmount = INPUT_USD_AMOUNT;
let poolName = DEFAULT_POOL_PARAMS.name;
let poolSymbol = DEFAULT_POOL_PARAMS.symbol;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--amount' && i + 1 < args.length) {
usdAmount = parseFloat(args[i + 1]);
i++;
} else if (args[i] === '--name' && i + 1 < args.length) {
poolName = args[i + 1];
i++;
} else if (args[i] === '--symbol' && i + 1 < args.length) {
poolSymbol = args[i + 1];
i++;
}
}
// Update pool params with parsed values
DEFAULT_POOL_PARAMS.name = poolName;
DEFAULT_POOL_PARAMS.symbol = poolSymbol;
try {
// Step 1: Fetch prices
const prices = await fetchCoinGeckoPrices();
// Step 2: Calculate token amounts
const tokenAmounts = calculateTokenAmounts(prices, usdAmount);
//
// // Step 3: Connect to wallet
console.log(`\n[~] Connecting to sender wallet at ${RPC_URL}...`);
const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);
console.log(`[+] Connected. Using sender wallet: ${wallet.address}`);
console.log(`[+] Receiver wallet: ${RECEIVER_ADDRESS}`);
//
// Step 4: Check balances
await checkBalances(provider, wallet, tokenAmounts, RECEIVER_ADDRESS);
// // Step 5: Approve tokens
if (NETWORK === 'mockchain' && currentConfig.receiverPrivateKey) {
// On mockchain, use receiver wallet for approvals
await approveTokens(provider, tokenAmounts, currentConfig.receiverPrivateKey);
} else if (NETWORK === 'mainnet') {
// On mainnet, use the main wallet (payer and receiver are the same)
await approveTokens(provider, tokenAmounts, PRIVATE_KEY);
}
// Step 6: Create pool
await createPool(wallet, tokenAmounts);
console.log(`\n${'='.repeat(70)}`);
console.log(`Success! Pool created with real-time price-based deposits.`);
console.log(`${'='.repeat(70)}\n`);
} catch (error) {
console.error(`\n${'='.repeat(70)}`);
console.error(`[!] Error: ${error.message}`);
console.error(`${'='.repeat(70)}\n`);
process.exit(1);
}
}
// Run the main function
main().catch(error => {
console.error('[!] Unexpected error:', error);
process.exit(1);
});