Web3Py代码中BSC交易报错:value字段无效的技术问询
问题解决:Web3Py在BSC交易中出现
TypeError: Transaction had invalid fields: {'value': '0.005'} 问题原因
Web3Py要求交易的value字段必须是以wei为单位的整数,你输入的0.005是原生代币(BNB)的人类可读数量,直接赋值会触发格式校验错误。不管转成int还是float都不行:转int会丢失小数部分,转float存在精度问题,Web3不接受浮点类型的value值。
解决方案
1. 正确转换代币单位
必须使用w3.toWei()函数将人类可读的代币数量转换为wei单位的整数,这个函数是Web3Py的标准工具,不会导致超额转账,只要你输入的数值正确就没问题。BSC的原生代币单位和ETH一致,用ether作为单位参数(1 BNB = 10^18 wei)。
2. 修正代码
修改amount_to_send的处理逻辑,同时补充BSC测试网的连接配置:
from web3 import Web3 # 连接BSC测试网节点 w3 = Web3(Web3.HTTPProvider('https://data-seed-prebsc-1-s1.binance.org:8545/')) # 验证连接状态 assert w3.is_connected(), "Failed to connect to BSC Testnet" # BSC测试网链ID为97 chain_id = 97 def buy_coin_token(): from_acc = input("Sender acc:").strip() private_key = input("Senders private key:").strip() to_acc = input("Receiver acc/contract address:").strip() # 转换输入金额为float后,转成wei单位的整数 amount_to_send = float(input("Amount to send:").strip()) amount_wei = w3.toWei(amount_to_send, 'ether') gas = int(input("Gas:").strip()) # 建议用gwei输入gas价格,再转成wei更符合交易习惯 gas_price = w3.toWei(input("Gas price (gwei):").strip(), 'gwei') nonce = w3.eth.getTransactionCount(from_acc) tx = { 'nonce': nonce, 'to': to_acc, 'value': amount_wei, # 使用转换后的wei整数 'gas': gas, 'gasPrice': gas_price, 'chainId': chain_id # 测试网必须指定链ID,避免交易被重放到主网 } signed_tx = w3.eth.account.signTransaction(tx, private_key) tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) # 转换哈希为可读的十六进制字符串 print(f"Your transaction hash is {w3.toHex(tx_hash)}")
关键说明
w3.toWei(0.005, 'ether')会精确计算出0.005 BNB对应的wei数量(即5000000000000000 wei),安全可靠。- 测试网交易必须指定
chainId,BSC测试网chainId为97,主网为56,可防止交易被恶意重放到其他链。 - gas price用gwei输入再转换,更贴合区块链交易的常规操作习惯。
内容的提问来源于stack exchange,提问作者Gekaz
相关产品推荐
相关产品推荐

