首页 > 解决方案 > 如何修复:TypeError:需要一个类似字节的对象,而不是“str”

问题描述

我最近开始编程。我正在尝试在 Ropsten 的帮助下模拟以太坊交易。当我尝试使用 Django 的 shell 运行函数 (sendTransaction ("message")) 时,我收到此错误:TypeError: a bytes-like object is required, not 'str'。完整的错误轨迹如下:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\Francesco\bakeka\bloggo\utils.py", line 18, in sendTransaction
    tx = w3.eth.sendTransaction(signedTx.rawTransaction)
  File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 577, in send_transaction
    return self._send_transaction(transaction)
  File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\module.py", line 53, in caller
    (method_str, params), response_formatters = method.process_params(module, *args, **kwargs)  # noqa: E501
  File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 179, in process_params
    params = self.input_munger(module, args, kwargs)
  File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\method.py", line 168, in input_munger
    root_munger(module, *args, **kwargs),
  File "C:\Users\Francesco\bakeka\globale\lib\site-packages\web3\eth.py", line 120, in send_transaction_munger
    if 'from' not in transaction and is_checksum_address(self.default_account):
TypeError: a bytes-like object is required, not 'str'

(Francesco 是我的用户名, bakeka 是我的项目,globale 是我的 venv)

from web3 import Web3

def sendTransaction(message):
    w3 = Web3(Web3.HTTPProvider('My Ropsten Ip'))
    address = 'my addres'
    privateKey = 'my private key'
    nonce = w3.eth.getTransactionCount(address)
    gasPrice = w3.eth.gasPrice
    value = w3.toWei(0, 'ether')
    signedTx = w3.eth.account.signTransaction(dict(
        nonce = nonce,
        gasPrice = gasPrice,
        gas = 10000,
        to = '0x0000000000000000000000000000000000000000',
        value = value,
        data = message.encode('utf-8'),
    ), privateKey)
    tx = w3.eth.sendTransaction(signedTx.rawTransaction)
    txId = w3.toHex(tx)
    return txId

你能帮助我吗?谢谢大家!!

标签: pythondjangoutf-8ethereumencode

解决方案


推荐阅读