1
0

test-copy.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/env node
  2. /**
  3. * Test Copy Script
  4. * Directly test the copy functionality for a specific parent position
  5. *
  6. * Usage:
  7. * node test-copy.js <parent_position_address> [target_usd_value]
  8. *
  9. * Examples:
  10. * # Use parent position value (default)
  11. * node test-copy.js Cbgjt5zfXd9QTpneDdADc9cKYwXxXRfe57cyfmBbQM41
  12. *
  13. * # Use specific target value (e.g., from transaction analysis)
  14. * node test-copy.js Cbgjt5zfXd9QTpneDdADc9cKYwXxXRfe57cyfmBbQM41 13.55
  15. */
  16. import { ByrealAPI, JupiterSwapper } from './src/services/index.js';
  17. import { CONFIG } from './src/config/index.js';
  18. import { logger, setLogLevel, formatUsd } from './src/utils/index.js';
  19. // Set log level to see detailed info
  20. setLogLevel('info');
  21. const PARENT_POSITION = process.argv[2] || '7rxWLdhk6Hk914QSBBztXJ35DUs4exr7mFJJdYWR2YNw';
  22. const MANUAL_TARGET_VALUE = parseFloat(process.argv[3]) || 0; // Optional: manual target value
  23. async function testCopy() {
  24. console.log('═══════════════════════════════════════════');
  25. console.log('🧪 Test Copy Script');
  26. console.log(`📍 Parent Position: ${PARENT_POSITION}`);
  27. if (MANUAL_TARGET_VALUE > 0) {
  28. console.log(`💰 Using Manual Target Value: $${MANUAL_TARGET_VALUE}`);
  29. }
  30. console.log('═══════════════════════════════════════════\n');
  31. // Step 1: Fetch parent position details
  32. console.log('Step 1: Fetching parent position details...');
  33. const parentDetail = await ByrealAPI.getPositionDetail(PARENT_POSITION);
  34. if (!parentDetail) {
  35. console.error('❌ Failed to fetch position detail');
  36. process.exit(1);
  37. }
  38. const poolInfo = parentDetail.pool;
  39. if (!poolInfo) {
  40. console.error('❌ Pool info not found');
  41. process.exit(1);
  42. }
  43. console.log('✅ Position details:');
  44. console.log(` Pool: ${poolInfo.mintA?.symbol}/${poolInfo.mintB?.symbol}`);
  45. console.log(` Token A: ${poolInfo.mintA?.address}`);
  46. console.log(` Token B: ${poolInfo.mintB?.address}`);
  47. // Get correct field names
  48. const nftMint = parentDetail.nftMintAddress || parentDetail.nftMint;
  49. const poolAddress = parentDetail.pool?.poolAddress || parentDetail.poolAddress;
  50. // Get base value for calculation
  51. const parentUsdValue = parseFloat(parentDetail.totalDeposit || parentDetail.totalUsdValue || parentDetail.liquidityUsd || 0);
  52. // Use manual target value if provided, otherwise use parent value
  53. const targetUsdValue = MANUAL_TARGET_VALUE > 0 ? MANUAL_TARGET_VALUE : parentUsdValue;
  54. console.log(` NFT Mint: ${nftMint}`);
  55. console.log(` Pool Address: ${poolAddress}`);
  56. console.log(` Parent Position Value: $${parentUsdValue}`);
  57. if (MANUAL_TARGET_VALUE > 0) {
  58. console.log(` ⚠️ Using Target Value: $${targetUsdValue} (not parent value!)`);
  59. } else {
  60. console.log(` Using Value: $${targetUsdValue}`);
  61. }
  62. // Step 2: Calculate copy amount
  63. console.log('\nStep 2: Calculating copy amount...');
  64. const copyUsdValue = Math.min(
  65. targetUsdValue * CONFIG.COPY_MULTIPLIER,
  66. CONFIG.MAX_USD_VALUE
  67. );
  68. console.log(` Base Value: $${targetUsdValue}`);
  69. console.log(` Multiplier: ${CONFIG.COPY_MULTIPLIER}x`);
  70. console.log(` Calculated: $${(targetUsdValue * CONFIG.COPY_MULTIPLIER).toFixed(2)}`);
  71. console.log(` Max Allowed: $${CONFIG.MAX_USD_VALUE}`);
  72. console.log(` ✅ Final Copy Amount: $${copyUsdValue}`);
  73. if (copyUsdValue < CONFIG.MIN_USD_VALUE) {
  74. console.error(`❌ Copy value $${copyUsdValue} below minimum $${CONFIG.MIN_USD_VALUE}`);
  75. process.exit(1);
  76. }
  77. // Step 3: Calculate token amounts
  78. console.log('\nStep 3: Calculating token amounts...');
  79. console.log(` Calling Byreal API with maxUsdValue: $${copyUsdValue}`);
  80. const calculation = await ByrealAPI.calculatePosition(
  81. PARENT_POSITION,
  82. copyUsdValue,
  83. nftMint
  84. );
  85. if (!calculation) {
  86. console.error('❌ Calculation failed');
  87. process.exit(1);
  88. }
  89. console.log('✅ Calculation result from Byreal API:');
  90. console.log(` Token A: ${calculation.tokenA?.amount} ${calculation.tokenA?.symbol} ($${calculation.tokenA?.valueUsd})`);
  91. console.log(` Token B: ${calculation.tokenB?.amount} ${calculation.tokenB?.symbol} ($${calculation.tokenB?.valueUsd})`);
  92. console.log(` Estimated Total: $${calculation.estimatedValue}`);
  93. console.log(`\n ⚠️ Note: These amounts are based on copy value $${copyUsdValue},`);
  94. console.log(` not the full parent position value ($${parentUsdValue})!`);
  95. // Debug: Check if amount is token quantity or USD value
  96. console.log('\n 🔍 Checking token amounts:');
  97. console.log(` Token A amount field: ${calculation.tokenA?.amount} (type: ${typeof calculation.tokenA?.amount})`);
  98. console.log(` Token A valueUsd field: ${calculation.tokenA?.valueUsd}`);
  99. console.log(` Token B amount field: ${calculation.tokenB?.amount} (type: ${typeof calculation.tokenB?.amount})`);
  100. console.log(` Token B valueUsd field: ${calculation.tokenB?.valueUsd}`);
  101. console.log(` If amount ≈ valueUsd, then amount is USD value, not token quantity!`);
  102. // Step 4: Check balances and swap
  103. console.log('\nStep 4: Checking balances and swapping...');
  104. const swapper = new JupiterSwapper();
  105. const tokenA = calculation.tokenA;
  106. const tokenB = calculation.tokenB;
  107. // Token A
  108. console.log(`\n Token A (${tokenA.symbol}):`);
  109. const tokenABalance = await swapper.getTokenBalance(tokenA.address);
  110. const requiredAmountA = parseFloat(tokenA.amount);
  111. const swapAmountA = requiredAmountA * 1.1;
  112. console.log(` Balance: ${tokenABalance.toFixed(6)}`);
  113. console.log(` Required: ${requiredAmountA.toFixed(6)}`);
  114. console.log(` With 10% buffer: ${swapAmountA.toFixed(6)}`);
  115. if (tokenABalance < requiredAmountA * 0.95) {
  116. console.log(` ⚠️ Insufficient balance, need to swap from USDC`);
  117. // Ask for confirmation
  118. console.log('\n Ready to swap. Continue? (Ctrl+C to cancel)');
  119. await new Promise(resolve => setTimeout(resolve, 3000));
  120. const success = await swapper.swapIfNeeded(
  121. 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  122. tokenA.address,
  123. swapAmountA,
  124. tokenA.decimals
  125. );
  126. if (!success) {
  127. console.error('❌ Failed to acquire Token A');
  128. process.exit(1);
  129. }
  130. } else {
  131. console.log(` ✅ Balance sufficient`);
  132. }
  133. // Token B
  134. console.log(`\n Token B (${tokenB.symbol}):`);
  135. const tokenBBalance = await swapper.getTokenBalance(tokenB.address);
  136. const requiredAmountB = parseFloat(tokenB.amount);
  137. const swapAmountB = requiredAmountB * 1.1;
  138. console.log(` Balance: ${tokenBBalance.toFixed(6)}`);
  139. console.log(` Required: ${requiredAmountB.toFixed(6)}`);
  140. console.log(` With 10% buffer: ${swapAmountB.toFixed(6)}`);
  141. if (tokenBBalance < requiredAmountB * 0.95) {
  142. console.log(` ⚠️ Insufficient balance, need to swap from USDC`);
  143. const success = await swapper.swapIfNeeded(
  144. 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  145. tokenB.address,
  146. swapAmountB,
  147. tokenB.decimals
  148. );
  149. if (!success) {
  150. console.error('❌ Failed to acquire Token B');
  151. process.exit(1);
  152. }
  153. } else {
  154. console.log(` ✅ Balance sufficient`);
  155. }
  156. // Step 5: Execute copy
  157. console.log('\n═══════════════════════════════════════════');
  158. console.log('Step 5: Ready to execute copy!');
  159. console.log('═══════════════════════════════════════════');
  160. console.log(`Parent Position: ${PARENT_POSITION}`);
  161. console.log(`NFT Mint: ${nftMint}`);
  162. console.log(`Copy Amount: $${copyUsdValue}`);
  163. console.log('\n⚠️ This will execute the actual copy transaction!');
  164. console.log('Executing copy...');
  165. const success = await ByrealAPI.copyPosition(
  166. nftMint,
  167. PARENT_POSITION,
  168. copyUsdValue
  169. );
  170. if (success) {
  171. console.log('\n✅ Copy executed successfully!');
  172. } else {
  173. console.log('\n❌ Copy failed!');
  174. process.exit(1);
  175. }
  176. console.log('\n═══════════════════════════════════════════');
  177. console.log('Test completed');
  178. console.log('═══════════════════════════════════════════');
  179. }
  180. testCopy().catch(error => {
  181. console.error('Fatal error:', error);
  182. process.exit(1);
  183. });