乐闻世界logo
搜索文章和话题

Python 如何在以太坊区块链上创建合约?

5 个月前提问
4 个月前修改
浏览次数51

1个答案

1

在以太坊区块链上创建智能合约通常涉及几个步骤,包括编写合约、部署合约以及与合约交互。使用 Python 进行这些操作主要通过 Web3.py 库,这是一个用于与以太坊节点交互的强大库。以下是创建和部署智能合约的基本步骤:

第一步:安装 Web3.py

在开始之前,需要确保你的系统中已安装 Web3.py。可以使用 pip 安装:

bash
pip install web3

第二步:编写智能合约

智能合约通常使用 Solidity 语言编写。以下是一个简单的 ERC-20 代币合约的例子:

solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Token { string public name = "Sample Token"; string public symbol = "SMP"; uint public totalSupply = 1000000; mapping(address => uint) balances; constructor() { balances[msg.sender] = totalSupply; } function transfer(address to, uint amount) public { require(balances[msg.sender] >= amount, "Not enough tokens"); balances[msg.sender] -= amount; balances[to] += amount; } function balanceOf(address account) public view returns (uint) { return balances[account]; } }

第三步:编译合约

将 Solidity 合约编译成 ABI(应用二进制接口)和字节码,这些是部署合约到以太坊时需要的。可以使用 solc 或在线 IDE 如 Remix 进行编译。

第四步:连接到以太坊网络

使用 Web3.py 连接到以太坊网络,可以是主网、测试网或本地节点。

python
from web3 import Web3 # 连接到本地节点 web3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545')) # 检查连接是否成功 print(web3.isConnected())

第五步:部署合约

加载合约的 ABI 和字节码,然后使用一个账户将其部署到网络上。

python
# 加载账户(假设已有私钥) account = web3.eth.account.privateKeyToAccount('YOUR_PRIVATE_KEY_HERE') # 加载合约 ABI 和字节码 contract = web3.eth.contract(abi=contract_abi, bytecode=contract_bytecode) # 构建交易 construct_txn = contract.constructor().buildTransaction({ 'from': account.address, 'nonce': web3.eth.getTransactionCount(account.address), 'gas': 1728712, 'gasPrice': web3.toWei('21', 'gwei') }) # 签名交易 signed = account.sign_transaction(construct_txn) # 发送交易 tx_hash = web3.eth.sendRawTransaction(signed.rawTransaction) # 等待交易完成 tx_receipt = web3.eth.waitForTransactionReceipt(tx_hash) # 获取合约地址 contract_address = tx_receipt.contractAddress

第六步:与合约交互

一旦合约部署完成,就可以通过合约地址和 ABI 使用 Web3.py 进行交互了。

python
# 实例化合约 deployed_contract = web3.eth.contract(address=contract_address, abi=contract_abi) # 调用合约函数 balance = deployed_contract.functions.balanceOf(account.address).call() print(f"Balance: {balance}")

这些步骤概述了使用 Python 在以太坊上创建和部署智能合约的过程。需要注意的是,进行实际部署时,应确保正确管理私钥和遵守网络的安全实践。

2024年6月29日 12:07 回复

你的答案