基于Raydium的Solana限价买入$MAGA机器人交易失败求助
我正在开发一款基于Raydium的Solana机器人,实现限价买入$MAGA代币的功能,但每次运行代码时交易均无法成功执行。从运行日志可见,create_exchange接口返回{'id': '03c2fd251bb64b3a85a3207deae7b010', 'success': False},后续调用create_transaction接口也返回{'id': '64218b3c90b943d0a1069e43248f406f', 'success': False},最终触发KeyError:'swapTransaction'报错。我已尝试调试代码、调大滑点和手续费,查阅Solana Python相关文档未找到有效解决方法,怀疑问题出在API链接上。
核心代码
# Returns the swap_transaction to be manipulated in sendTransaction() async def create_transaction(quote: dict, input_token_mint, output_token_mint) -> dict: log_transaction.info(f"""Soltrade is creating transaction for the following quote: {quote}""") if 'error' in quote: log_transaction.error(f"Error in quote: {quote['error']}") raise Exception(f"Error in quote: {quote['error']}") pool_id = get_pool_id(input_token_mint) #pool_id = "9XsGAA3xHC6gqRgThRrcaUPU6jzerZacWgfyMb17579t" # Parameters used for the Raydium POST request parameters = { "quoteResponse": quote, "userPublicKey": str(configs['public_address']), "wrapUnwrapSOL": True, "computeUnitPriceMicroLamports": 20 * 3_000_000 # fee of roughly $.4 :shrug: } #9XsGAA3xHC6gqRgThRrcaUPU6jzerZacWgfyMb17579t # Returns the JSON parsed response of Jupiter async with httpx.AsyncClient() as client: response = await client.post(f"https://api.raydium.io/v2/swap?poolId={pool_id}", json=parameters) exchange_data = response.json() pprint(f"TRANSACTION CREATE:\n{exchange_data}") return exchange_data async def perform_swap(sent_amount: float, price_limit, sent_token_mint: str, mode : str): global position log_general.info("Soltrade is taking a limit position.") #TODO: fetch the current price and create a limit order current_price = get_price(sent_token_mint) base_token = await get_token_decimals(sent_token_mint) quote = trans = opts = txid = tx_error = None is_tx_successful = False for i in range(0,3): if not is_tx_successful: try: if (mode == "buy") or (mode == "sell"): quote = await create_exchange(sent_amount, sent_token_mint, mode) trans = await create_transaction(quote, sent_token_mint, SOL_MINT_ADDRESS) print(f"TRANS:\n{trans}") opts = TxOpts(skip_preflight=False, preflight_commitment="confirmed", last_valid_block_height=find_last_valid_block_height()) txid = send_transaction(trans["swapTransaction"], opts) for i in range(3): await asyncio.sleep(35) tx_error = find_transaction_error(txid) if not tx_error: is_tx_successful = True break else: log_general.info(f"Price hasn't reached {price_limit}. Waiting for the next opportunity.") await asyncio.sleep(60) continue #current_price = get_price(sent_token_mint) except Exception as e: if RPCException: print(traceback.format_exc()) log_general.warning(f"Soltrade failed to complete transaction {i}. Retrying.") continue else: raise for i in range(0, 3): try: await asyncio.sleep(35) tx_error = find_transaction_error(txid) if not tx_error: is_tx_successful = True break except TypeError as e: print(traceback.format_exc()) log_general.warning("Soltrade failed to verify the existence of the transaction. Retrying.") continue else: break
错误日志
2024-05-27 14:19:22 Soltrade has detected a buy signal. 2024-05-27 14:19:22 Soltrade is taking a limit position. Response: SOL 2024-05-27 14:19:22 Soltrade is creating exchange for 12.103126943600001 dollars in ('', '') Pool ID: 8sLbNZoA1cfnvMJLPfp98ZLAnFSYCFApfJKMbiXNLwxj ('EXCHANGE CREATED:\n' "{'id': '03c2fd251bb64b3a85a3207deae7b010', 'success': False}") 2024-05-27 14:19:23 Soltrade is creating transaction for the following quote: {'id': '03c2fd251bb64b3a85a3207deae7b010', 'success': False} ('TRANSACTION CREATE:\n' "{'id': '64218b3c90b943d0a1069e43248f406f', 'success': False}") TRANS: {'id': '64218b3c90b943d0a1069e43248f406f', 'success': False} Traceback (most recent call last): File "/Users/dekahalane/soltrade-1/soltrade/transactions.py", line 204, in perform_swap txid = send_transaction(trans["swapTransaction"], opts) KeyError: 'swapTransaction' 2024-05-27 14:19:24 Soltrade failed to complete transaction 0. Retrying.
1. 校验API接口与参数合法性
- 确认Raydium v2 Swap接口的正确路径:当前使用的
https://api.raydium.io/v2/swap?poolId={pool_id}可能不符合官方规范,需核对官方文档的接口路由(比如是否应为/v2/swap/create-transaction)。 - 在
create_exchange函数中打印完整响应内容,包括HTTP状态码和返回的错误字段,仅靠success:False无法定位具体失败原因。
2. 拦截无效的quote参数
当前代码未对create_exchange返回的失败结果做判断,直接将无效的quote传入create_transaction,必然导致后续调用失败。需在perform_swap中增加校验:
quote = await create_exchange(sent_amount, sent_token_mint, mode) # 新增:判断报价是否创建成功 if not quote.get('success'): log_general.error(f"报价创建失败: {quote}") continue # 跳过后续步骤,直接重试
3. 验证池ID(pool_id)正确性
日志中的池ID8sLbNZoA1cfnvMJLPfp98ZLAnFSYCFApfJKMbiXNLwxj需确认是否为$MAGA与SOL的Raydium流动性池地址。可通过Solscan或Raydium官网查询该地址对应的交易对,若池ID错误,API会直接返回失败。
4. 增强错误捕获与日志输出
- 在
create_transaction中打印HTTP响应的状态码和原始文本,便于排查API调用问题:
async with httpx.AsyncClient() as client: response = await client.post(f"https://api.raydium.io/v2/swap?poolId={pool_id}", json=parameters) print(f"API响应状态码: {response.status_code}") print(f"API响应内容: {response.text}") exchange_data = response.json()
- 在访问
trans["swapTransaction"]前,先判断交易创建是否成功,避免触发KeyError:
if not trans.get('success'): log_general.error(f"交易创建失败: {trans}") continue txid = send_transaction(trans["swapTransaction"], opts)
5. 检查手续费参数合理性
当前设置的computeUnitPriceMicroLamports=60000000(0.06 SOL)虽偏高,但并非核心问题。可结合Solana网络当前拥堵情况调整,但需优先解决前面的API调用失败问题。
内容的提问来源于stack exchange,提问作者Angela

