推荐编程语言:Python
推荐编辑器:Pycharm & VSCode
推荐类库:Web3
推荐辅助AI:GPT & Deepseek & Claude & Grok
推荐翻译软件:沉浸式翻译 (推荐搭配gpt 4o mini 兼顾质量和价格)
安装依赖:
1
| pip install web3==7.10.0
|
阅读文档:
https://web3py.readthedocs.io/en/v7.10.0/quickstart.html
连接Web3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| from web3 import Web3
rpc_url = "https://rpc.hoodi.ethpandaops.io"
w3 = Web3(Web3.HTTPProvider(rpc_url))
if w3.is_connected(): print("成功连接到网络!") block_number = w3.eth.block_number print(f"当前区块号: {block_number}")
chain_id = w3.eth.chain_id print(f"链 ID: {chain_id}") else: print("连接失败!")
|
创建帐号:
1 2 3 4 5
| from web3 import Web3
w3 = Web3() acc = w3.eth.account.create() print(f'private key={w3.to_hex(acc.key)}, account={acc.address}')
|
设置环境变量:
不建议直接在代码里面使用私钥。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import os from eth_account import Account from eth_account.signers.local import LocalAccount from web3 import Web3
def set_private_key(): """设置私钥到环境变量""" try: existing_key = os.environ.get("PRIVATE_KEY") if existing_key: print(f"已存在的私钥: {existing_key}") return existing_key
private_key = input("请输入私钥 (需要包含0x前缀): ").strip() if not private_key.startswith("0x"): private_key = "0x" + private_key os.system(f'setx PRIVATE_KEY "{private_key}"') os.environ["PRIVATE_KEY"] = private_key print("私钥已成功设置到环境变量") return private_key except Exception as e: print(f"设置私钥时出错: {str(e)}") return None
def main(): try: os.system('cls') print("=" * 50) print("私钥环境变量设置工具") print("=" * 50)
private_key = set_private_key() if not private_key: input("\n设置失败,按回车键退出...") return
w3 = Web3(Web3.HTTPProvider('https://ethereum-sepolia.publicnode.com'))
account: LocalAccount = Account.from_key(private_key) print(f"\n私钥设置成功!") print(f"钱包地址: {account.address}") print("\n你现在可以在其他脚本中通过环境变量使用这个私钥") print("示例代码:") print("import os") print("private_key = os.environ.get('PRIVATE_KEY')") input("\n按回车键退出...")
except Exception as e: print(f"\n发生错误: {str(e)}") input("\n按回车键退出...")
if __name__ == "__main__": main()
|
读取环境变量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| from web3 import Web3 import os from eth_account import Account from datetime import datetime
def get_account_balance(w3: Web3, address: str) -> float: """获取账户余额并转换为ETH单位""" balance_wei = w3.eth.get_balance(address) balance_eth = w3.from_wei(balance_wei, 'ether') return balance_eth
def get_private_key(): """获取私钥(先尝试从环境变量获取,如果失败则从注册表读取)""" private_key = os.environ.get("PRIVATE_KEY")
if not private_key: try: import winreg key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ) private_key, _ = winreg.QueryValueEx(key, "PRIVATE_KEY") winreg.CloseKey(key) os.environ["PRIVATE_KEY"] = private_key except Exception as e: print(f"从注册表读取私钥失败: {e}") return None
return private_key
def main(): try: print("=" * 50) print("Hoodi网络连接测试") print("=" * 50)
rpc_url = "https://rpc.hoodi.ethpandaops.io" w3 = Web3(Web3.HTTPProvider(rpc_url))
if not w3.is_connected(): print("\n❌ 连接失败!") input("\n按回车键退出...") return
print("\n✅ 成功连接到Hoodi网络!")
block_number = w3.eth.block_number print(f"当前区块号: {block_number}")
chain_id = w3.eth.chain_id print(f"链 ID: {chain_id}")
private_key = get_private_key() if private_key: account = Account.from_key(private_key) balance = get_account_balance(w3, account.address)
print("\n当前账户信息:") print(f"地址: {account.address}") print(f"余额: {balance:.6f} ETH") else: print("\n⚠️ 未找到私钥,无法显示账户信息") print("提示: 请先运行第5个示例设置私钥")
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"\n查询时间: {current_time}")
input("\n按回车键退出...")
except Exception as e: print(f"\n发生错误: {str(e)}") input("\n按回车键退出...")
if __name__ == "__main__": main()
|