diff --git a/src/Managing.Web3Proxy/src/plugins/custom/gmx.ts b/src/Managing.Web3Proxy/src/plugins/custom/gmx.ts index f572a518..737adffd 100644 --- a/src/Managing.Web3Proxy/src/plugins/custom/gmx.ts +++ b/src/Managing.Web3Proxy/src/plugins/custom/gmx.ts @@ -520,20 +520,12 @@ async function approveTokenForContract( try { const contractAddress = getContract(sdk.chainId, contractName as ContractName); - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:523',message:'Allowance check start',data:{ticker:fromTicker,contractName,contractAddress,tokenAddress:fromTokenData.address,requiredAmount:fromTokenAmount.toString(),account:sdk.account},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{}); - // #endregion - const currentAllowance = await getTokenAllowance( sdk.account, fromTokenData.address, contractAddress ); - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:530',message:'Allowance check result',data:{ticker:fromTicker,contractName,currentAllowance:currentAllowance.toString(),requiredAmount:fromTokenAmount.toString(),isSufficient:currentAllowance>=fromTokenAmount},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'A'})}).catch(()=>{}); - // #endregion - console.log(`Current allowance for ${fromTicker}:`, currentAllowance); console.log(`Required amount:`, fromTokenAmount); @@ -543,10 +535,6 @@ async function approveTokenForContract( // Approve maximum amount (2^256 - 1) to avoid future approval transactions const maxApprovalAmount = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:537',message:'Approval transaction start',data:{ticker:fromTicker,contractName,contractAddress,approvalAmount:maxApprovalAmount.toString()},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{}); - // #endregion - const approvalHash = await approveContractImpl( sdk.account, fromTokenData.address, @@ -556,21 +544,13 @@ async function approveTokenForContract( true // waitForConfirmation = true (already default, but being explicit) ); - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:545',message:'Approval transaction hash received',data:{ticker:fromTicker,contractName,approvalHash},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{}); - // #endregion - console.log(`✅ Token approval successful! Hash: ${approvalHash}`); console.log(`📝 Approved maximum amount ${fromTicker} for ${contractName}`); - console.log(`🔍 DEBUG: Contract ${contractName} address: ${contractAddress}`); - console.log(`🔍 DEBUG: Token ${fromTicker} address: ${fromTokenData.address}`); - console.log(`🔍 DEBUG: Account: ${sdk.account}`); // Verify the approval transaction was actually mined by checking the receipt try { const receipt = await sdk.publicClient.getTransactionReceipt({ hash: approvalHash as `0x${string}` }); console.log(`✅ Approval transaction confirmed in block ${receipt.blockNumber}`); - console.log(`🔍 DEBUG: Approval transaction status: ${receipt.status === 'success' ? 'success' : 'failed'}`); if (receipt.status !== 'success') { throw new Error(`Approval transaction failed: ${approvalHash}`); @@ -580,8 +560,7 @@ async function approveTokenForContract( // Continue anyway as approveContractImpl should have already waited } - // Wait additional time for state to propagate across RPC nodes - console.log(`⏳ Waiting 5 seconds for state to propagate across RPC nodes...`); + // Wait for state to propagate across RPC nodes await new Promise(resolve => setTimeout(resolve, 5000)); // Verify allowance multiple times to ensure state has propagated @@ -591,8 +570,6 @@ async function approveTokenForContract( contractAddress ); - console.log(`🔍 DEBUG: Post-approval allowance (first read): ${postApprovalAllowance.toString()}`); - // If still insufficient, wait more and retry with fresh RPC call if (postApprovalAllowance < fromTokenAmount) { console.log(`⏳ Allowance still insufficient, waiting 5 more seconds and retrying...`); @@ -602,17 +579,8 @@ async function approveTokenForContract( fromTokenData.address, contractAddress ); - console.log(`🔍 DEBUG: Post-approval allowance (second read): ${postApprovalAllowance.toString()}`); } - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:575',message:'Post-approval allowance check',data:{ticker:fromTicker,contractName,postApprovalAllowance:postApprovalAllowance.toString(),requiredAmount:fromTokenAmount.toString(),isSufficient:postApprovalAllowance>=fromTokenAmount},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'B'})}).catch(()=>{}); - // #endregion - - console.log(`🔍 DEBUG: Final post-approval allowance: ${postApprovalAllowance.toString()}`); - console.log(`🔍 DEBUG: Required amount: ${fromTokenAmount.toString()}`); - console.log(`🔍 DEBUG: Is sufficient: ${postApprovalAllowance >= fromTokenAmount}`); - if (postApprovalAllowance < fromTokenAmount) { console.error(`❌ CRITICAL: Approval failed! Allowance ${postApprovalAllowance.toString()} is less than required ${fromTokenAmount.toString()}`); throw new Error(`Token approval failed: allowance ${postApprovalAllowance.toString()} is less than required ${fromTokenAmount.toString()}`); @@ -621,9 +589,6 @@ async function approveTokenForContract( console.log(`✅ Sufficient allowance already exists for ${fromTicker}`); } } catch (allowanceError) { - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:550',message:'Allowance approval error',data:{ticker:fromTicker,contractName,error:allowanceError instanceof Error ? allowanceError.message : 'Unknown error'},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'E'})}).catch(()=>{}); - // #endregion console.warn('Could not check or approve token allowance:', allowanceError); throw new Error(`Failed to handle token allowance: ${allowanceError instanceof Error ? allowanceError.message : 'Unknown error'}`); } @@ -870,10 +835,6 @@ export const openGmxPositionImpl = async ( hasSufficientBalance: usdcBalance >= collateralAmount }); - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:835',message:'USDC balance check',data:{usdcBalance:usdcBalance.toString(),requiredAmount:collateralAmount.toString(),hasSufficientBalance:usdcBalance>=collateralAmount,quantity,currentPrice},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'F'})}).catch(()=>{}); - // #endregion - if (usdcBalance < collateralAmount) { const errorMsg = `Insufficient USDC balance: need ${Number(collateralAmount) / 1e6} USDC, but only have ${Number(usdcBalance) / 1e6} USDC`; console.error(`❌ ${errorMsg}`); @@ -942,51 +903,13 @@ export const openGmxPositionImpl = async ( console.log('✅ Token allowances verified, proceeding with position opening...'); - // #region agent log + // Verify allowances before executing order const exchangeRouterAddress = getContract(sdk.chainId, "ExchangeRouter"); - const orderVaultAddress = getContract(sdk.chainId, "OrderVault"); - const syntheticsRouterAddress = getContract(sdk.chainId, "SyntheticsRouter"); - - console.log(`🔍 DEBUG: ExchangeRouter address: ${exchangeRouterAddress}`); - console.log(`🔍 DEBUG: OrderVault address: ${orderVaultAddress}`); - console.log(`🔍 DEBUG: SyntheticsRouter address: ${syntheticsRouterAddress}`); - console.log(`🔍 DEBUG: USDC token address: ${collateralToken.address}`); - console.log(`🔍 DEBUG: Required collateral amount: ${collateralAmount.toString()}`); - - // Force a fresh state read by waiting and checking multiple times - console.log(`⏳ Waiting 3 seconds for state to propagate...`); await new Promise(resolve => setTimeout(resolve, 3000)); - // Check allowance using getTokenAllowance (which uses multicall, but we'll verify with multiple reads) - console.log(`🔍 Reading ExchangeRouter allowance...`); const finalExchangeRouterAllowance = await getTokenAllowance(sdk.account, collateralToken.address, exchangeRouterAddress); - console.log(`🔍 Reading OrderVault allowance...`); - const finalOrderVaultAllowance = await getTokenAllowance(sdk.account, collateralToken.address, orderVaultAddress); - - console.log(`🔍 Reading SyntheticsRouter allowance...`); - const finalSyntheticsRouterAllowance = await getTokenAllowance(sdk.account, collateralToken.address, syntheticsRouterAddress); - - // Double-check ExchangeRouter with a second read to catch any caching issues - await new Promise(resolve => setTimeout(resolve, 1000)); - const secondExchangeRouterAllowance = await getTokenAllowance(sdk.account, collateralToken.address, exchangeRouterAddress); - console.log(`🔍 Second ExchangeRouter allowance read: ${secondExchangeRouterAllowance.toString()}`); - if (finalExchangeRouterAllowance !== secondExchangeRouterAllowance) { - console.warn(`⚠️ Allowance values differ between reads! First: ${finalExchangeRouterAllowance.toString()}, Second: ${secondExchangeRouterAllowance.toString()}`); - } - - console.log(`🔍 DEBUG: ExchangeRouter allowance (direct read): ${finalExchangeRouterAllowance.toString()}`); - console.log(`🔍 DEBUG: OrderVault allowance (direct read): ${finalOrderVaultAllowance.toString()}`); - console.log(`🔍 DEBUG: SyntheticsRouter allowance (direct read): ${finalSyntheticsRouterAllowance.toString()}`); - console.log(`🔍 DEBUG: ExchangeRouter sufficient: ${finalExchangeRouterAllowance >= collateralAmount}`); - console.log(`🔍 DEBUG: OrderVault sufficient: ${finalOrderVaultAllowance >= collateralAmount}`); - - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:850',message:'Pre-order allowance verification (direct read)',data:{exchangeRouterAddress,orderVaultAddress,syntheticsRouterAddress,exchangeRouterAllowance:finalExchangeRouterAllowance.toString(),orderVaultAllowance:finalOrderVaultAllowance.toString(),syntheticsRouterAllowance:finalSyntheticsRouterAllowance.toString(),requiredAmount:collateralAmount.toString()},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'C'})}).catch(()=>{}); - // #endregion - - // Double-check ExchangeRouter allowance is sufficient before proceeding if (finalExchangeRouterAllowance < collateralAmount) { - console.error(`❌ CRITICAL: ExchangeRouter allowance ${finalExchangeRouterAllowance.toString()} is insufficient for required ${collateralAmount.toString()}`); throw new Error(`Insufficient ExchangeRouter allowance: ${finalExchangeRouterAllowance.toString()} < ${collateralAmount.toString()}`); } @@ -1003,35 +926,12 @@ export const openGmxPositionImpl = async ( console.log('🚀 Executing position order...'); - // Final allowance check RIGHT before transaction execution - // Also check the current block number to ensure we're reading from the latest state - const currentBlock = await sdk.publicClient.getBlockNumber(); - console.log(`🔍 DEBUG: Current block number: ${currentBlock.toString()}`); - - const finalCheckAllowance = await getTokenAllowance(sdk.account, collateralToken.address, exchangeRouterAddress); - console.log(`🔍 DEBUG: Final allowance check RIGHT before order execution: ${finalCheckAllowance.toString()}`); - console.log(`🔍 DEBUG: Required amount: ${collateralAmount.toString()}`); - console.log(`🔍 DEBUG: Is sufficient: ${finalCheckAllowance >= collateralAmount}`); - - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:850',message:'Final allowance check before execution',data:{blockNumber:currentBlock.toString(),finalAllowance:finalCheckAllowance.toString(),requiredAmount:collateralAmount.toString(),isSufficient:finalCheckAllowance>=collateralAmount},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'E'})}).catch(()=>{}); - // #endregion - - if (finalCheckAllowance < collateralAmount) { - console.error(`❌ CRITICAL: ExchangeRouter allowance ${finalCheckAllowance.toString()} is insufficient RIGHT before execution!`); - throw new Error(`Insufficient ExchangeRouter allowance at execution time: ${finalCheckAllowance.toString()} < ${collateralAmount.toString()}`); - } - if (direction === TradeDirection.Long) { await sdk.orders.long(params); } else { await sdk.orders.short(params); } - // #region agent log - fetch('http://127.0.0.1:7242/ingest/556ee8d6-75a9-41e6-9311-6e6215b38a77',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({location:'gmx.ts:837',message:'Order execution completed',data:{direction},timestamp:Date.now(),sessionId:'debug-session',runId:'run1',hypothesisId:'D'})}).catch(()=>{}); - // #endregion - console.log('✅ Position order executed successfully'); return "";