Web3.py

無法使用 web3.py 獲得 nonce 含義

  • March 29, 2022

我正在關注 freecodecamp solidity 教程,不幸的是,當我嘗試獲取 nonce 含義時出現錯誤。我使用 web3.py 和 ganache,如教程中所示。這是我的程式碼:

from solcx import compile_standard, install_solc
import json
from web3 import Web3

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

install_solc("0.6.0")
compiled_sol = compile_standard(
   {
       "language": "Solidity",
       "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
       "settings": {
           "outputSelection": {
               "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.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 = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]

# for connecting to ganache
w3 = Web3(Web3.HTTPProvider("http://0.0.0.0:8545"))
chain_id = 1337
my_address = "0xC674eC6962Ba5dEe7a1409187DE523663dbffB14"
private_key = "0x0e6322ac24bdac2508bc4b888486e98dd4a090d954b47fcbc9c1efc06970953"

# create the contract in python
SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
# get the latest transaction
nonce = w3.eth.getTransactionCount(my_address)
print(nonce)

至少當我列印它給我一個答案時,它確實創建了一份契約。但是當我嘗試創建一個隨機數時,它會出現下一個錯誤:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='0.0.0.0', port=8545): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001B91C7468E0>: Failed to establish a new connection: [WinError 10049]

有誰知道問題出在哪裡?

http://0.0.0.0:8545不是有效的 Ethereum JSON-RPC 節點 URL。請獲取一個有效的節點。

下面是一些例子

請仔細檢查 Ganache 上 RPC 伺服器的地址

引用自:https://ethereum.stackexchange.com/questions/114561