龙空技术网

使用Python完成EVM链余额查询和交易发送

一起玩转web3 21

前言:

此刻你们对“python读取余额表”都比较看重,你们都想要知道一些“python读取余额表”的相关内容。那么小编同时在网摘上网罗了一些对于“python读取余额表””的相关内容,希望各位老铁们能喜欢,朋友们快快来学习一下吧!

前面我们讲过了通过web3库创建钱包,其实web3库还有很多功能,今天就给大家讲一下使用web3库查询账号余额,以及发送交易。

准备工作

查询目前主要是主网的token,比如polygon上面的matic,bsc的bnb钱包需要有余额,可以使用测试链和测试币(比如,goerli测试网和goerliETH,本教程使用的是gitshock测试链和代币GTFX)

代码实现

1.导入依赖库

from web3 import Web3, HTTPProviderfrom web3.gas_strategies.rpc import rpc_gas_price_strategy

2.创建web3连接

# 创建web3连接def creatWeb3(rpc):    web3 = Web3(HTTPProvider(rpc))    # 查看区块高度    blockNumber = web3.eth.blockNumber    print("当前区块高度:", blockNumber)    return web3

3.查询余额

# 查看余额def checkBlance(web3, addr, type):    blance = web3.fromWei(web3.eth.get_balance(addr), "ether")    print(f"账户 {addr} 的{type}余额是: {blance} ")    return blance

4.发送交易

def transerTo(web3, addrFrom, key, addrTo, num, type, chainId):    account_from = {        "private_key": key,        "address": addrFrom,    }    print(        f'准备从账户 {addrFrom} 转账{num}个{type} 到账户{addrTo}'    )    # 查询当前价格    print("查询当前gas是:", web3.eth.generate_gas_price())    # 设置gas价格    web3.eth.set_gas_price_strategy(rpc_gas_price_strategy)    # 创建交易签名    tx_create = web3.eth.account.sign_transaction(        {            "nonce": web3.eth.get_transaction_count(addrFrom),            "gasPrice": web3.eth.generate_gas_price(),            "gas": 21000,            "to": addrTo,            "chainId": chainId,            "value": web3.toWei(num, "ether"),  # 转账数量        },        key,    )    # 发送和等待    tx_hash = web3.eth.send_raw_transaction(tx_create.rawTransaction)    tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)    print(f"交易成功!hash: {tx_receipt.transactionHash.hex()}")

5.调用

if __name__ == '__main__':    address_from = "0xf0f9c45fd3b733d274448a161A2942B12F606420" #发款地址    address_to = "0xe0252BC89C76Bdc4c9d09f96F10901DED7E542ef" #收款地址    rpc = "; #RPC    key = 'xxx' #钱包私钥    num = '1' #转账数量    type = 'GTFX' #代币符号    chainId = 212 #链ID    web3 = creatWeb3(rpc)    # 查看转账前余额    print('转账前余额~~~~')    checkBlance(web3,address_from,type)    checkBlance(web3, address_to,type)    # #发送交易    transerTo(web3, address_from, key, address_to, num,type,chainId)    # 查看转账后余额    print('转账后余额~~~~')    checkBlance(web3, address_from, type)    checkBlance(web3, address_to, type)

执行结果:

交易查看:

0xe4eb6a32e5bfd7f1589e222558a07188f007768be107642b30d0f7b1baf3ad92

非常不凑巧,gitshock项目的测试网浏览器()挂掉了,没有上截图。

以上就是使用web3库,完成了余额查询和发送交易操作,还有其他功能比如签名等等,后面还将给大家带来合约交互的教程

如果有其他问题可以通过公众号「python玩转」联系作者

标签: #python读取余额表