Web3 api 主要提供web3连接,数据编码格式转换
python安装web3:
pip3 install web3
1.调用api连接链rpc
'''导入Web3模块'''
from web3 import Web3
'''连接rpc环境'''
Web3(Web3.HTTPProvider('http://127.0.0.1:7890'))
2.web3.toHex
根据输入的格式解码UTF-8字符串
from web.auto import w3
Web3.to_text(text='cowmö')
'cowmö'
Web3.to_text(b'cowm\xc3\xb6')
'cowmö'
Web3.to_text(hexstr='636f776dc3b6')
'cowmö'
3.web3.toBytes
根据输入的格式编码UTF-8字符串
from web.auto import w3
Web3.toBytes(0)
b'\x00'
Web3.toBytes(0x000F)
b'\x0f'
Web3.toBytes(False)
b'\x00'
Web3.toBytes(True)
b'\x01'
Web3.toBytes(hexstr='0x000F')
b'\x00\x0f'
Web3.toBytes(hexstr='000F')
b'\x00\x0f'
Web3.toBytes(text='')
b''
Web3.toBytes(text='cowmö')
b'cowm\xc3\xb6'
4.web3.toInt
根据输入的格式转码Int整数
from web.auto import w3
Web3.to_int(0)
0
Web3.to_int(0x000F)
15
Web3.to_int(b'\x00\x0F')
15
Web3.to_int(False)
0
Web3.to_int(True)
1
Web3.to_int(hexstr='0x000F')
15
Web3.to_int(hexstr='000F')
15
5.web3.toWei
根据传递金额数量增加对应精度
from web.auto import w3
Web3.toWei(1, 'ether')
1000000000000000000
Web3.toWei(1, 'mwei')
1000000
6.web3.fromWei
根据传递金额数量减少对应精度
from web.auto import w3
Web3.fromWei(1000000000000000000, 'ether')
1
Web3.fromWei(1000000, 'mwei')
1
7.Web3.is_address
检查0x地址是否是有效地址
from web.auto import w3
Web3.is_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601')
True
8.web3.keccak
通过传递的数据进行 Keccak-256编码
from web.auto import w3
Web3.keccak(text='txt')
HexBytes('0xd7278090a36507640ea6b7a0034b69b0d240766fa3f98e3722be93c613b29d2e')
9.web3.soliditySha3
根据传递的参数类型和参数值计算出 Keccak-256 对应HX
from web.auto import w3
Web3.solidity_keccak(['bool'], [True])
"0x5fe7f977e71dba2ea1a68e21057beebb9be2ac30c6410aa38d4f3fbe41dcffd2"
Web3.solidity_keccak(['uint8', 'uint8', 'uint8'], [97, 98, 99])
"0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"
Web3.solidity_keccak(['address'], ["ethereumfoundation.eth"])
"0x913c99ea930c78868f1535d34cd705ab85929b2eaaf70fcd09677ecd6e5d75e9"