使用 Python 和 Web3.py 部署智能合约到区块链:完整指南
使用 Python 和 Web3.py 部署智能合约到区块链:完整指南
本指南将带您逐步了解如何使用 Python 和 Web3.py 库编写和部署智能合约到区块链。通过清晰的步骤和示例代码,您可以轻松上手智能合约开发。
1. 安装 Web3.py 库
在终端输入以下命令:
pip install web3
2. 连接以太坊节点
from web3 import Web3
# 连接以太坊节点
web3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
# 检查连接状态
if web3.isConnected():
print('连接成功')
else:
print('连接失败')
3. 编写智能合约
pragma solidity ^0.6.0;
contract MyContract {
uint public myNumber;
function setNumber(uint _number) public {
myNumber = _number;
}
}
4. 编译智能合约
在终端输入以下命令:
solc --abi MyContract.sol -o build
5. 部署智能合约
from web3 import Web3
import json
# 连接以太坊节点
web3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
# 读取 abi 文件
with open('build/MyContract_sol_MyContract.abi') as f:
abi = json.load(f)
# 读取 bin 文件
with open('build/MyContract_sol_MyContract.bin') as f:
bytecode = f.read()
# 获取账户
account = web3.eth.accounts[0]
# 创建合约实例
MyContract = web3.eth.contract(abi=abi, bytecode=bytecode)
# 部署合约
tx_hash = MyContract.constructor().transact({'from': account})
tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
# 获取合约地址
contract_address = tx_receipt.contractAddress
print('合约地址:', contract_address)
# 获取合约实例
my_contract = web3.eth.contract(address=contract_address, abi=abi)
# 调用合约方法
tx_hash = my_contract.functions.setNumber(10).transact({'from': account})
web3.eth.waitForTransactionReceipt(tx_hash)
# 获取合约数据
print('myNumber:', my_contract.functions.myNumber().call())
完整代码
from web3 import Web3
import json
# 连接以太坊节点
web3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
# 检查连接状态
if web3.isConnected():
print('连接成功')
else:
print('连接失败')
# 读取 abi 文件
with open('build/MyContract_sol_MyContract.abi') as f:
abi = json.load(f)
# 读取 bin 文件
with open('build/MyContract_sol_MyContract.bin') as f:
bytecode = f.read()
# 获取账户
account = web3.eth.accounts[0]
# 创建合约实例
MyContract = web3.eth.contract(abi=abi, bytecode=bytecode)
# 部署合约
tx_hash = MyContract.constructor().transact({'from': account})
tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash)
# 获取合约地址
contract_address = tx_receipt.contractAddress
print('合约地址:', contract_address)
# 获取合约实例
my_contract = web3.eth.contract(address=contract_address, abi=abi)
# 调用合约方法
tx_hash = my_contract.functions.setNumber(10).transact({'from': account})
web3.eth.waitForTransactionReceipt(tx_hash)
# 获取合约数据
print('myNumber:', my_contract.functions.myNumber().call())
参考文献
- https://web3py.readthedocs.io/en/stable/
- https://solidity.readthedocs.io/en/v0.6.0/
- https://remix.ethereum.org/
原文地址: https://www.cveoy.top/t/topic/mYTQ 著作权归作者所有。请勿转载和采集!