使用 web3.py 进行合约交互

# 部署合约

import json
from web3 import Web3, HTTPProvider
private_key = [钱包私钥]
wallet = Web3.toChecksumAddress([钱包地址])
w3 = Web3(HTTPProvider([链的RPC]))
abi = json.loads([合约的ABI])
code = [合约的字节码]
newContract = w3.eth.contract(bytecode=code, abi=abi)
nonce = w3.eth.getTransactionCount(wallet)
gasPrice = w3.toWei('10', 'gwei')
gasLimit = 4000000
tx = {
    'nonce': nonce,
    'gas': gasLimit,
    'gasPrice': gasPrice,
    'from': wallet,
    'chainId': w3.eth.chainId
}
transaction = newContract.constructor().buildTransaction(tx)
signed_tx = w3.eth.account.sign_transaction(transaction, private_key)
tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
transaction_hash = w3.toHex(tx_hash)
tx_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
print(tx_receipt.contractAddress)

# 调用合约中的函数

import json
import time
from web3 import Web3, HTTPProvider
contract_address = [合约地址]
private_key = [钱包私钥]
wallet = Web3.toChecksumAddress([钱包地址])
w3 = Web3(HTTPProvider([RPC]))
w3.eth.defaultAccount = wallet
abi = json.loads([合约的ABI])
contract = w3.eth.contract(address=contract_address, abi=abi)
nonce = w3.eth.getTransactionCount(wallet)
gasPrice = w3.toWei('5', 'gwei')
gasLimit = 4000000
tx = {
    'nonce': nonce,
    'gas': gasLimit,
    'gasPrice': gasPrice,
    'from': wallet,
    'value': w3.toWei(0.01,'ether')
}
transaction = contract.functions.create().buildTransaction(tx)
signed_tx = w3.eth.account.sign_transaction(transaction, private_key)
tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
transaction_hash = w3.toHex(tx_hash)
tx_receipt = w3.eth.wait_for_transaction_receipt(transaction_hash)
print(transaction_hash)

# 向某一个地址转账

import json
import time
from web3 import Web3, HTTPProvider
private_key = [钱包私钥]
wallet = Web3.toChecksumAddress([钱包地址])
w3 = Web3(HTTPProvider([RPC]))
w3.eth.defaultAccount = wallet
to = Web3.toChecksumAddress([要转账的地址])
nonce = w3.eth.get_transaction_count(wallet)
tx = {
    'nonce': nonce,
    'to': to,
    'gas': 4000000,
    'gasPrice': w3.toWei('30', 'gwei'),
    'value': w3.toWei(0.01, 'ether'),
    'chainId': w3.eth.chainId
}
# 签名交易
signed_tx = w3.eth.account.sign_transaction(tx, private_key)
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)

# 查询一个地址的 ETH

import json
import time
from web3 import Web3, HTTPProvider
w3 = Web3(HTTPProvider([RPC]))
print(w3.fromWei(w3.eth.getBalance([需要查询的地址]), 'Ether'))
更新于 阅读次数