PatrickAlphaC / web3_py_simple_storage

47 stars 78 forks source link

A bunch of errors at SimpleStorage.constructor().buildTransaction | w3.eth.getTransactionCount #25

Closed leitecombacalhau closed 2 years ago

leitecombacalhau commented 2 years ago

Hi, I'm getting several errors with the w3.eth.getTransactionCount. Is anyone else having these errors? I've read through the web3.py docs and searched it online but I didn't manage to find the answer.

This is my code:

import json

from web3 import Web3

from solcx import compile_standard
from os import getenv
from dotenv import load_dotenv

load_dotenv()

with open("./contracts/SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

# Solidity source code
compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                }
            }
        },
    },
    solc_version="0.6.0",
)

with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
    "bytecode"
]["object"]

# get abi
abi = json.loads(
    compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["metadata"]
)["output"]["abi"]

# For connecting to ganache
w3 = Web3(Web3.HTTPProvider("http://0.0.0.0:8545"))
chain_id = 1337
my_address = "0x8A004259EF5504DEEA89b10F14dAac0b1Fd8bB2C"
private_key = getenv("PRIVATE_KEY")

# Create the contract in Python
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
# Get the latest transaction
nonce = w3.eth.getTransactionCount(my_address) # <- if I comment out this line of code the no error is thrown
print(nonce)
# # Submit the transaction that deploys the contract
# transaction = SimpleStorage.constructor().buildTransaction(
#     {
#         "chainId": chain_id,
#         "from": my_address,
#         "nonce": nonce,
#     }
# )
# # Sign the transaction
# signed_txn = w3.eth.account.sign_transaction(transaction, private_key=private_key)
# print(signed_txn)

and the error:

INFO: Could not find files for the given pattern(s).
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection
    raise err
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection
    sock.connect(sa)
OSError: [WinError 10049] O endereço pedido não é válido no seu contexto

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 239, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1276, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1322, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1271, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 1031, in _send_output
    self.send(msg)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 969, in send
    self.connect()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 205, in connect
    conn = self._new_conn()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 186, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0000020C455BB520>: Failed to establish a new connection: [WinError 10049] O endereço pedido não é válido no seu contexto

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\util\retry.py", line 574, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='0.0.0.0', port=8545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020C455BB520>: Failed to establish a new connection: [WinError 10049] O endereço pedido não é válido no seu contexto'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\Learn\SolidityCourse\demos\web3_py_simple_storage\deploy.py", line 56, in <module>
    nonce = w3.eth.getTransactionCount(my_address) # <- if I comment out this line of code the no error is thrown
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\module.py", line 57, in caller
    result = w3.manager.request_blocking(method_str,
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 197, in request_blocking
    response = self._make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 150, in _make_request
    return request_func(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\gas_price_strategy.py", line 90, in middleware
    return make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\attrdict.py", line 33, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\formatting.py", line 94, in middleware
    response = make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\buffered_gas_estimate.py", line 40, in middleware
    return make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\middleware\exception_retry_request.py", line 105, in middleware
    return make_request(method, params)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\providers\rpc.py", line 88, in make_request
    raw_response = make_post_request(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\_utils\request.py", line 48, in make_post_request
    response = session.post(endpoint_uri, data=data, *args, **kwargs)  # type: ignore
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000020C455BB520>: Failed to establish a new connection: [WinError 10049] O endereço pedido não é válido no seu contexto'))

Here's a screenshot of how my Ganache looks like: ganache screenshot Any help would be very appreciated.

leitecombacalhau commented 2 years ago

Ok, so I figured it out. I changed the Ganache server hostname to 127.0.0.1 and now it's working. But I'm getting a new error now with

transaction = SimpleStorage.constructor().buildTransaction(
    {
        "chainId": chain_id,
        "from": my_address,
        "nonce": nonce,
    }
)

Error(s):

INFO: Could not find files for the given pattern(s).
C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\eth.py:633: UserWarning: There was an issue with the method eth_maxPriorityFeePerGas. Calculating using eth_feeHistory.
  warnings.warn(
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\eth.py", line 631, in max_priority_fee
    return self._max_priority_fee()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\module.py", line 57, in caller
    result = w3.manager.request_blocking(method_str,
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 198, in request_blocking
    return self.formatted_response(response,
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 171, in formatted_response
    raise ValueError(response["error"])
ValueError: {'message': 'Method eth_maxPriorityFeePerGas not supported.', 'code': -32000, 'data': {'stack': 'Error: Method eth_maxPriorityFeePerGas not supported.\n    at GethApiDouble.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\geth_api_double.js:70:16)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at GethDefaults.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\gethdefaults.js:15:12)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at SubscriptionSubprovider.FilterSubprovider.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\subproviders\\filters.js:89:7)\n    at SubscriptionSubprovider.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\subproviders\\subscriptions.js:137:49)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at DelayedBlockFilter.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\delayedblockfilter.js:31:3)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at RequestFunnel.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\requestfunnel.js:32:12)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at Web3ProviderEngine._handleAsync (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:123:3)\n    at Timeout._onTimeout (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:107:12)\n    at listOnTimeout (internal/timers.js:531:17)\n    at processTimers (internal/timers.js:475:7)', 'name': 'Error'}}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\Learn\SolidityCourse\demos\web3_py_simple_storage\deploy.py", line 58, in <module>
    transaction = SimpleStorage.constructor().buildTransaction(
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\eth_utils\decorators.py", line 18, in _wrapper
    return self.method(obj, *args, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\contract.py", line 684, in buildTransaction
    return fill_transaction_defaults(self.web3, built_transaction)
  File "cytoolz/functoolz.pyx", line 250, in cytoolz.functoolz.curry.__call__
    return self.func(*args, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\_utils\transactions.py", line 114, in fill_transaction_defaults
    default_val = default_getter(web3, transaction)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\_utils\transactions.py", line 64, in <lambda>
    web3.eth.max_priority_fee + (2 * web3.eth.get_block('latest')['baseFeePerGas'])
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\eth.py", line 637, in max_priority_fee
    return fee_history_priority_fee(self)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\_utils\fee_utils.py", line 45, in fee_history_priority_fee
    fee_history = eth.fee_history(*PRIORITY_FEE_HISTORY_PARAMS)  # type: ignore
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\eth.py", line 863, in fee_history
    return self._fee_history(block_count, newest_block, reward_percentiles)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\module.py", line 57, in caller
    result = w3.manager.request_blocking(method_str,
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 198, in request_blocking
    return self.formatted_response(response,
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\web3\manager.py", line 171, in formatted_response
    raise ValueError(response["error"])
ValueError: {'message': 'Method eth_feeHistory not supported.', 'code': -32000, 'data': {'stack': 'Error: Method eth_feeHistory not supported.\n    at GethApiDouble.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\geth_api_double.js:70:16)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at GethDefaults.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\gethdefaults.js:15:12)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at SubscriptionSubprovider.FilterSubprovider.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\subproviders\\filters.js:89:7)\n    at SubscriptionSubprovider.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\subproviders\\subscriptions.js:137:49)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at DelayedBlockFilter.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\delayedblockfilter.js:31:3)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at RequestFunnel.handleRequest (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\lib\\subproviders\\requestfunnel.js:32:12)\n    at next (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:136:18)\n    at Web3ProviderEngine._handleAsync (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:123:3)\n    at Timeout._onTimeout (C:\\Program Files\\WindowsApps\\GanacheUI_2.5.4.0_x64__5dg5pnz03psnj\\app\\resources\\static\\node\\node_modules\\ganache-core\\node_modules\\web3-provider-engine\\index.js:107:12)\n    at listOnTimeout (internal/timers.js:531:17)\n    at processTimers (internal/timers.js:475:7)', 'name': 'Error'}}
leitecombacalhau commented 2 years ago

Just found the solution.

transaction = SimpleStorage.constructor().buildTransaction(
    {
        "chainId": chain_id,
        "from": my_address,
        "gasPrice": w3.eth.gas_price, # <- missing this argument
        "nonce": nonce,
    }
)

https://stackoverflow.com/a/70111921 Everything is working fine now.