当前位置:   article > 正文

Python web3 api调用

python web3

Python web3 api调用

1.简介

Web3 api 主要提供web3连接,数据编码格式转换

2.web3安装

python安装web3:

pip3 install web3 
  • 1
3.常用web3 API

1.调用api连接链rpc

'''导入Web3模块'''
from  web3 import Web3

'''连接rpc环境'''
Web3(Web3.HTTPProvider('http://127.0.0.1:7890'))
  • 1
  • 2
  • 3
  • 4
  • 5

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ö'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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'
  • 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

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

5.web3.toWei
根据传递金额数量增加对应精度

from web.auto import w3


Web3.toWei(1, 'ether')
1000000000000000000

Web3.toWei(1, 'mwei')
1000000
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

6.web3.fromWei
根据传递金额数量减少对应精度

from web.auto import w3


Web3.fromWei(1000000000000000000, 'ether')
1

Web3.fromWei(1000000, 'mwei')
1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

7.Web3.is_address
检查0x地址是否是有效地址

from web.auto import w3


Web3.is_address('0xd3CdA913deB6f67967B99D67aCDFa1712C293601')
True
  • 1
  • 2
  • 3
  • 4
  • 5

8.web3.keccak
通过传递的数据进行 Keccak-256编码

from web.auto import w3


Web3.keccak(text='txt')
HexBytes('0xd7278090a36507640ea6b7a0034b69b0d240766fa3f98e3722be93c613b29d2e')
  • 1
  • 2
  • 3
  • 4
  • 5

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"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/55778
推荐阅读
相关标签
  

闽ICP备14008679号