Python开发Solana加密交易Telegram机器人遇类型转换错误
Solana交易ID类型转换错误解决方案:str转Signature失败
问题原因
新版本solana-py库的get_transaction方法要求传入Signature对象,而非原始字符串类型的交易ID。直接传递清理后的Base58字符串会触发类型转换错误:argument 'signature': 'str' object cannot be converted to 'Signature'。
解决步骤
- 导入
solana.publickey模块中的Signature类 - 将清理后的交易ID字符串通过
Signature.from_string()方法转换为Signature对象 - 新增转换过程的异常捕获,处理无效Base58格式的情况
修改后的完整代码
from solana.rpc.api import Client # type: ignore from solana.publickey import Signature # 新增导入Signature类 import re # Set up your Solana RPC endpoint SOLANA_RPC_URL = "https://api.mainnet-beta.solana.com" solana_client = Client(SOLANA_RPC_URL) # Function to sanitize transaction ID def sanitize_transaction_id(transaction_id: str) -> str: """ Removes invalid characters from a transaction ID, ensuring it is a valid Base58 string. """ return re.sub(r'[^123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]', '', transaction_id) # Function to check a Solana transaction def check_transaction(transaction_id: str): try: # Sanitize the transaction ID sanitized_transaction_id = sanitize_transaction_id(transaction_id) print(f"Raw Transaction ID: {transaction_id}") print(f"Sanitized Transaction ID: {sanitized_transaction_id}") # Ensure the sanitized transaction ID is 88 characters long if len(sanitized_transaction_id) != 88: # Solana transaction signatures are typically 88 Base58 characters raise ValueError("Transaction ID length is invalid.") # 将字符串转换为Signature对象 try: signature = Signature.from_string(sanitized_transaction_id) except ValueError as ve: raise ValueError("Invalid Base58 transaction signature format.") from ve # Fetch the transaction details using the Solana RPC API print("Attempting to fetch transaction details...") transaction = solana_client.get_transaction(signature) # 传递Signature对象而非字符串 if not transaction or not transaction.get("result"): print("Transaction not found or incomplete.") return print("Transaction details fetched successfully!") print(transaction) except ValueError as ve: print(f"Validation Error: {ve}") except Exception as e: print(f"Unexpected Error: {e}") # Example usage if __name__ == "__main__": # Replace with your test transaction ID test_transaction_id = "2JNwfJbNmTFkH2YuWWErWTaNpMpbqETguMiLFWqFE6mMy8LiNrf3N9dYZc66NwowybPd1JaE1thTBT36cRx4h7ki" check_transaction(test_transaction_id)
关键修改点说明
- 新增
from solana.publickey import Signature导入语句 - 在长度校验后,添加字符串转Signature对象的逻辑,并捕获转换失败的异常
- 将
get_transaction的参数从字符串改为转换后的signature对象
内容的提问来源于stack exchange,提问作者Abhinav Sharma
相关产品推荐
相关产品推荐

