test-copy.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 prices = await swapper.getTokenPrices([tokenA.address, tokenB.address]);
  109. const needSwapUsd = async (token, valueUsd) => {
  110. const requiredWithBuffer = valueUsd * BUFFER_PCT;
  111. const balance = await swapper.getTokenBalance(token.address);
  112. const price = prices[token.address]?.price ?? 0;
  113. const currentValueUsd = balance * price;
  114. if (currentValueUsd >= requiredWithBuffer) {
  115. return { skip: true, currentValueUsd, requiredWithBuffer };
  116. }
  117. return { skip: false, swapUsd: requiredWithBuffer - currentValueUsd, currentValueUsd, requiredWithBuffer };
  118. };
  119. const valueA = parseFloat(tokenA.valueUsd) || 0;
  120. if (valueA > 0) {
  121. const planA = await needSwapUsd(tokenA, valueA);
  122. if (planA.skip) {
  123. console.log(` Token A (${tokenA.symbol}): 已有 $${planA.currentValueUsd.toFixed(2)} >= 需要 $${planA.requiredWithBuffer.toFixed(2)},跳过 swap`);
  124. } else {
  125. console.log(` Token A (${tokenA.symbol}): 已有 $${planA.currentValueUsd.toFixed(2)},需 $${planA.requiredWithBuffer.toFixed(2)}(含 20% 缓冲),swap $${planA.swapUsd.toFixed(2)}`);
  126. console.log(' Ready to swap. Continue? (Ctrl+C to cancel)');
  127. await new Promise(resolve => setTimeout(resolve, 3000));
  128. const success = await swapper.swapIfNeeded(tokenA.address, planA.swapUsd);
  129. if (!success) {
  130. console.error('❌ Failed to acquire Token A');
  131. process.exit(1);
  132. }
  133. }
  134. }
  135. const valueB = parseFloat(tokenB.valueUsd) || 0;
  136. if (valueB > 0) {
  137. const planB = await needSwapUsd(tokenB, valueB);
  138. if (planB.skip) {
  139. console.log(` Token B (${tokenB.symbol}): 已有 $${planB.currentValueUsd.toFixed(2)} >= 需要 $${planB.requiredWithBuffer.toFixed(2)},跳过 swap`);
  140. } else {
  141. console.log(` Token B (${tokenB.symbol}): 已有 $${planB.currentValueUsd.toFixed(2)},需 $${planB.requiredWithBuffer.toFixed(2)}(含 20% 缓冲),swap $${planB.swapUsd.toFixed(2)}`);
  142. const success = await swapper.swapIfNeeded(tokenB.address, planB.swapUsd);
  143. if (!success) {
  144. console.error('❌ Failed to acquire Token B');
  145. process.exit(1);
  146. }
  147. }
  148. }
  149. // Step 5: Execute copy
  150. console.log('\n═══════════════════════════════════════════');
  151. console.log('Step 5: Ready to execute copy!');
  152. console.log('═══════════════════════════════════════════');
  153. console.log(`Parent Position: ${PARENT_POSITION}`);
  154. console.log(`NFT Mint: ${nftMint}`);
  155. console.log(`Copy Amount: $${copyUsdValue}`);
  156. console.log('\n⚠️ This will execute the actual copy transaction!');
  157. console.log('Executing copy...');
  158. const success = await ByrealAPI.copyPosition(
  159. nftMint,
  160. PARENT_POSITION,
  161. copyUsdValue
  162. );
  163. if (success) {
  164. console.log('\n✅ Copy executed successfully!');
  165. } else {
  166. console.log('\n❌ Copy failed!');
  167. process.exit(1);
  168. }
  169. console.log('\n═══════════════════════════════════════════');
  170. console.log('Test completed');
  171. console.log('═══════════════════════════════════════════');
  172. }
  173. testCopy().catch(error => {
  174. console.error('Fatal error:', error);
  175. process.exit(1);
  176. });