Solana Python交易脚本报错:Transaction无recent_blockhash属性及参数异常
问题解决:Solana Python交易脚本的两个错误处理
第一个错误:Transaction对象无recent_blockhash属性
错误原因
你使用solders.transaction.Transaction的构造方式完全错误:
Transaction类的构造参数并非([payer], message, blockhash),该类不支持直接传入payer密钥对和blockhash作为构造参数- 错误传参导致交易对象未正确初始化,进而无法访问或设置
recent_blockhash属性
修正方案
使用solders提供的Transaction.new_with_payer方法创建交易,手动设置区块哈希并完成签名:
# 获取最新区块哈希 blockhash_resp = await client.get_latest_blockhash() recent_blockhash = blockhash_resp.value.blockhash # 创建指定支付者的交易 tx_ata = Transaction.new_with_payer([create_ata_ix], payer.pubkey()) # 设置区块哈希 tx_ata.recent_blockhash = recent_blockhash # 用支付者密钥对完成交易签名 tx_ata.sign(payer) # 发送序列化后的交易 tx_hash = await client.send_raw_transaction( tx_ata.serialize(), opts=TxOpts(skip_preflight=True, preflight_commitment=Confirmed) ) await client.confirm_transaction(tx_hash, commitment="confirmed")
或者用更简洁的方式,直接调用client.send_transaction,它会自动处理区块哈希和签名流程:
tx_hash = await client.send_transaction( payer, # 签名者密钥对 msg, # 已构造的Message对象 opts=TxOpts(skip_preflight=True, preflight_commitment=Confirmed) ) await client.confirm_transaction(tx_hash.value, commitment="confirmed")
第二个错误:VersionedTransaction不接受payer参数
错误原因
solders.transaction.VersionedTransaction的构造函数没有payer这个关键字参数,它仅接受VersionedMessage对象和签名列表作为入参。你错误传递了不存在的参数导致报错。
修正方案
先通过VersionedMessage.compile构造版本化消息,再创建VersionedTransaction并完成签名:
from solders.transaction import VersionedTransaction, VersionedMessage # 获取最新区块哈希 blockhash_resp = await client.get_latest_blockhash() recent_blockhash = blockhash_resp.value.blockhash # 构造版本化消息,指定支付者和区块哈希 versioned_msg = VersionedMessage.compile( instructions=[create_ata_ix], payer=payer.pubkey(), recent_blockhash=recent_blockhash ) # 生成签名:用支付者密钥对消息字节签名 signature = payer.sign_message(versioned_msg.to_bytes()) # 创建版本化交易 tx_ata = VersionedTransaction(versioned_msg, [signature]) # 发送序列化后的交易 tx_hash = await client.send_raw_transaction( tx_ata.serialize(), opts=TxOpts(skip_preflight=True, preflight_commitment=Confirmed) ) await client.confirm_transaction(tx_hash, commitment="confirmed")
内容的提问来源于stack exchange,提问作者Wacky Alien League
相关产品推荐
相关产品推荐

