Python for web3 - 从钱包中获取余额
·
在本文中,我们将使用 web3 库从钱包中获取余额。如果你只是想要代码,这里是:
from web3 import Web3
# rpc urls are endpoints used to send and receive data to a specific blockchain
# here we're interacting with Polygon's testnet, the mumbai testnet
mumbai_rpc_url = "https://rpc-mumbai.maticvigil.com"
# The provider is your connection to a blockchain
web3 = Web3(Web3.HTTPProvider(mumbai_rpc_url))
#log if we're connected or not
print(web3.isConnected())
#get the blocknumber
print(web3.eth.blockNumber)
#get the balance
#balance is shown in Wei, which is a huge number. Wei is likes 'pennies' in the ethereum world
wallet_address = "0x55c9bBb71a5CC11c2f0c40362Bb691b33a78B764"
print(web3.eth.getBalance(wallet_address))
#balance here is formatted in ether,
balance = web3.eth.getBalance(wallet_address)
print(web3.fromWei(balance,"ether"))
让我们进入它
我们将首先设置我们的环境,然后深入研究代码。
设置我们的环境
我们需要做的第一件事是创建一个虚拟环境并安装 web3 库。
键入以下命令以创建虚拟环境并激活它。
python3 -m env ./myv
source ./myv/bin/activate
接下来我们需要 pip 安装 web3 库。
pip install web3
完成后,创建一个.py文件并打开您的代码编辑器。
编码时间
首先我们导入 web3 库。
from web3 import Web3
接下来我们需要连接到区块链。我们需要为此传递一个RPCurl。我要连接Mumbai网络,也就是Polygon的测试网络。
mumbai_rpc_url = "https://rpc-mumbai.maticvigil.com"
web3 = Web3(Web3.HTTPProvider(mumbai_rpc_url))
使用 web3 库,我们可以检查我们是否已连接
print(web3.isConnected())
现在要获得余额,我们调用方法getBalance,但首先我们需要告诉我们的程序我们要定位哪个钱包。
wallet_address = "0x55c9bBb71a5CC11c2f0c40362Bb691b33a78B764"
print(web3.eth.getBalance(wallet_address))
余额在Wei中返回,是一个超长的数字。魏兑以太币就像便士兑美元。唯一的区别是 100 便士等于 1 美元,而 1,000,000,000,000,000,000 wei (10^18) 等于 1 以太币。
因此,让我们将天平格式化为更易读的格式。
balance = web3.eth.getBalance(wallet_address)
print(web3.fromWei(balance,"ether"))
就是这样
通过几行代码,您已经使用 Python 与区块链进行交互。如果您正在寻找更多这样的代码片段,请查看我的Github repo或继续关注本系列的更多文章。
更多推荐

所有评论(0)