web3_demo.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # -*- coding: utf-8 -*-
  2. from web3 import Web3, HTTPProvider
  3. # 连接到以太坊节点
  4. w3 = Web3(HTTPProvider('http://127.0.0.1:8545'))
  5. # 检查是否连接成功
  6. if w3.isConnected():
  7. print("Connected to Ethereum node")
  8. else:
  9. print("Failed to connect to Ethereum node")
  10. exit()
  11. # 1. 获取最新区块号
  12. latest_block = w3.eth.block_number
  13. print(f"Latest block number: {latest_block}")
  14. # 2. 获取区块信息
  15. block = w3.eth.get_block(latest_block)
  16. print(f"Block info: {block}")
  17. # 3. 获取账户余额
  18. account = '0xYourAccountAddress' # 替换为你的账户地址
  19. balance = w3.eth.get_balance(account)
  20. print(f"Balance of {account}: {w3.fromWei(balance, 'ether')} ETH")
  21. # 4. 发送交易
  22. sender = '0xYourAccountAddress' # 替换为你的账户地址
  23. private_key = 'YourPrivateKey' # 替换为你的私钥
  24. receiver = '0xReceiverAddress' # 替换为接收方地址
  25. nonce = w3.eth.get_transaction_count(sender)
  26. tx = {
  27. 'nonce': nonce,
  28. 'to': receiver,
  29. 'value': w3.toWei(0.01, 'ether'),
  30. 'gas': 2000000,
  31. 'gasPrice': w3.toWei('50', 'gwei'),
  32. }
  33. signed_tx = w3.eth.account.sign_transaction(tx, private_key)
  34. tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
  35. print(f"Transaction hash: {w3.toHex(tx_hash)}")
  36. # 5. 与智能合约交互
  37. contract_address = '0xYourContractAddress' # 替换为合约地址
  38. contract_abi = [...] # 替换为合约的ABI
  39. contract = w3.eth.contract(address=contract_address, abi=contract_abi)
  40. # 调用合约的只读方法
  41. result = contract.functions.yourReadOnlyMethod().call()
  42. print(f"Result from contract: {result}")
  43. # 调用合约的写方法
  44. tx = contract.functions.yourWriteMethod(param1, param2).buildTransaction({
  45. 'nonce': w3.eth.get_transaction_count(sender),
  46. 'gas': 2000000,
  47. 'gasPrice': w3.toWei('50', 'gwei'),
  48. })
  49. signed_tx = w3.eth.account.sign_transaction(tx, private_key)
  50. tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
  51. print(f"Transaction hash: {w3.toHex(tx_hash)}")
  52. # 6. 监听事件
  53. event_filter = contract.events.YourEvent.createFilter(fromBlock='latest')
  54. print("Listening for events...")
  55. while True:
  56. for event in event_filter.get_new_entries():
  57. print(f"New event: {event}")
  58. # 7. 获取交易收据
  59. tx_receipt = w3.eth.get_transaction_receipt(tx_hash)
  60. print(f"Transaction receipt: {tx_receipt}")
  61. # 8. 获取交易详情
  62. tx_detail = w3.eth.get_transaction(tx_hash)
  63. print(f"Transaction detail: {tx_detail}")
  64. # 9. 获取日志
  65. logs = w3.eth.get_logs({
  66. 'fromBlock': 0,
  67. 'toBlock': 'latest',
  68. 'address': contract_address,
  69. })
  70. print(f"Logs: {logs}")
  71. # 10. 获取当前 Gas 价格
  72. gas_price = w3.eth.gas_price
  73. print(f"Current gas price: {w3.fromWei(gas_price, 'gwei')} gwei")
  74. # 11. 获取账户交易数量
  75. transaction_count = w3.eth.get_transaction_count(sender)
  76. print(f"Transaction count: {transaction_count}")
  77. # 12. 获取合约代码
  78. contract_code = w3.eth.get_code(contract_address)
  79. print(f"Contract code: {contract_code}")
  80. # 13. 获取账户存储
  81. storage = w3.eth.get_storage_at(contract_address, 0)
  82. print(f"Storage at position 0: {storage}")
  83. # 14. 获取账户 nonce
  84. nonce = w3.eth.get_transaction_count(sender)
  85. print(f"Account nonce: {nonce}")
  86. # 15. 获取区块 gas 限制
  87. gas_limit = w3.eth.get_block('latest')['gasLimit']
  88. print(f"Gas limit: {gas_limit}")
  89. # 16. 获取区块 gas 使用量
  90. gas_used = w3.eth.get_block('latest')['gasUsed']
  91. print(f"Gas used: {gas_used}")
  92. # 17. 获取区块 gas 费用
  93. gas_fee = gas_used * gas_price
  94. print(f"Gas fee: {w3.fromWei(gas_fee, 'ether')} ETH")