test-copy.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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: Swap by valueUsd + 20% buffer, 仅当当前持仓不足时才 swap
  103. console.log('\nStep 4: Check balance & swap (valueUsd + 20% buffer)...');
  104. const swapper = new JupiterSwapper();
  105. const tokenA = calculation.tokenA;
  106. const tokenB = calculation.tokenB;
  107. const BUFFER_PCT = 1.2;
  108. const checkAndSwap = async (label, token, valueUsd) => {
  109. const balance = await swapper.getTokenBalance(token.address);
  110. const requiredAmount = parseFloat(token.amount) || 0;
  111. const bufferedAmount = requiredAmount * BUFFER_PCT;
  112. const bufferedValueUsd = valueUsd * BUFFER_PCT;
  113. console.log(` ${label} (${token.symbol || token.address}): 余额=${balance}, 需要=${requiredAmount}, 含缓冲=${bufferedAmount.toFixed(6)}, valueUsd=$${valueUsd.toFixed(2)}, priceUsd=${token.priceUsd}`);
  114. if (requiredAmount > 0 && balance >= bufferedAmount) {
  115. console.log(` ✅ ${label}: 余额充足 ${balance} >= ${bufferedAmount.toFixed(6)},跳过 swap`);
  116. return true;
  117. }
  118. let swapUsd = bufferedValueUsd;
  119. if (requiredAmount > 0 && balance > 0) {
  120. const ratio = balance / bufferedAmount;
  121. swapUsd = bufferedValueUsd * (1 - ratio);
  122. }
  123. console.log(` ${label}: 余额不足,需 swap $${swapUsd.toFixed(2)}`);
  124. console.log(' Ready to swap. Continue? (Ctrl+C to cancel)');
  125. await new Promise(resolve => setTimeout(resolve, 3000));
  126. const success = await swapper.swapIfNeeded(token.address, swapUsd);
  127. if (!success) {
  128. console.error(`❌ Failed to acquire ${label}`);
  129. process.exit(1);
  130. }
  131. return true;
  132. };
  133. const valueA = parseFloat(tokenA.valueUsd) || 0;
  134. if (valueA > 0) {
  135. await checkAndSwap('Token A', tokenA, valueA);
  136. }
  137. const valueB = parseFloat(tokenB.valueUsd) || 0;
  138. if (valueB > 0) {
  139. await checkAndSwap('Token B', tokenB, valueB);
  140. }
  141. // Step 5: Execute copy
  142. console.log('\n═══════════════════════════════════════════');
  143. console.log('Step 5: Ready to execute copy!');
  144. console.log('═══════════════════════════════════════════');
  145. console.log(`Parent Position: ${PARENT_POSITION}`);
  146. console.log(`NFT Mint: ${nftMint}`);
  147. console.log(`Copy Amount: $${copyUsdValue}`);
  148. console.log('\n⚠️ This will execute the actual copy transaction!');
  149. console.log('Executing copy...');
  150. const success = await ByrealAPI.copyPosition(
  151. nftMint,
  152. PARENT_POSITION,
  153. copyUsdValue
  154. );
  155. if (success) {
  156. console.log('\n✅ Copy executed successfully!');
  157. } else {
  158. console.log('\n❌ Copy failed!');
  159. process.exit(1);
  160. }
  161. console.log('\n═══════════════════════════════════════════');
  162. console.log('Test completed');
  163. console.log('═══════════════════════════════════════════');
  164. }
  165. testCopy().catch(error => {
  166. console.error('Fatal error:', error);
  167. process.exit(1);
  168. });