Web3.py use detailed explanation

1. Installation

pip install web3

2. Use Web3

test provider

from web3 import Web3, EthereumTesterProvider
w3 = Web3(EthereumTesterProvider())

local provider

from web3 import Web3

# IPCProvider:
w3 = Web3(Web3.IPCProvider('./path/to/geth.ipc'))

# HTTPProvider:
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))

# WebsocketProvider:
w3 = Web3(Web3.WebsocketProvider('wss://127.0.0.1:8546'))

remote provider

The fastest way to interact with the Ethereum blockchain is to use a remote node provider such as Infura, Alchemy or QuickNode. You can connect to a remote node just like a local node by specifying an endpoint:

from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://<your-provider-url>'))
w3 = Web3(Web3.WebsocketProvider('wss://<your-provider-url>'))

Determine the connection status 

w3.isConnected()

3. Create an account

Create an account with web3

account = w3.eth.account.create()
print(account.address)

Create an account with eth_account

The effect is the same as web3, installing web3.py will automatically installeth-account

from eth_account import Account

account = Account.create()
print(account.address)
# 账户的私钥
print(account.key.hex())

Import accounts via private_key

from eth_account import Account
import json

key = '...'
account = Account.from_key(key)
print(account.address)

Get a list of accounts

accounts = w3.eth.accounts

get default account

w3.eth.default_account

4. Common methods 

Get the latest block

w3.eth.get_block('latest')

Get the number of blocks

w3.eth.block_number

Get block transaction

w3.eth.get_transaction_by_block(46147, 0)

get balance

balance = w3.eth.getBalance(account)

Send a transfer transaction 

params = {}
params['from'] = accounts[0] 
params['to'] = accounts[1]
params['value'] = w3.toWei(1, "ether")
tx_hash = w3.eth.sendTransaction(params)

Get transaction information 

tx = w3.eth.getTransaction(tx_hash)

Get transaction receipt

Returns null if the transaction is pending.

tx = w3.eth.getTransactionReceipt(tx_hash)

5. Contract call

contract instantiation

filePath = "/Users/XXXX/Solidity/USDT/contracts/usdt.json"
text = open(filePath, encoding='utf-8').read()
jsonObj = json.loads(text)
usdt_contract_addr = '合约地址'
usdt = w3.eth.contract(address=usdt_contract_addr, abi=jsonObj['abi'])

contract read operation

balance = usdt.functions.balanceOf(accounts[0]).call()

contract write operation

option = {'from': accounts[0], 'gas': 1000000}
usdt.functions.approve(usdt_contract_addr, 2000000).transact(option)

Signed contract write operation

options = {'gas': 1000000,
    'gasPrice': w3.toWei('21', 'gwei'),
    'from': account.address,
    'nonce': w3.eth.getTransactionCount(account.address)}
tx = usdt.functions.approve(usdt_contract_addr, 2000000).buildTransaction(options)
signed = account.signTransaction(tx) # 用账户对交易签名	
tx_id = w3.eth.sendRawTransaction(signed.rawTransaction) # 交易发送并获取交易id
print(tx_id.hex())

Guess you like

Origin blog.csdn.net/watson2017/article/details/122500681