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

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

准备工作

代码实现

1.导入依赖库

from web3 import Web3, HTTPProvider
from 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 = "https://rpc-testnet.gitshock.com/cartenz" #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项目的测试网浏览器(https://scan.gitshock.com/)挂掉了,没有上截图。

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


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

展开阅读全文

页面更新:2024-04-14

标签:余额   代币   区块   账户   钱包   高度   数量   功能   地址   测试

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top