Dapps开发包括三个简单的步骤:
在区块链网络上部署智能合约
从部署的智能合约中读取数据
将交易发送到部署的智能合约
pragma solidity^0.5.7;
contract greeter{
string greeting;
function greet(string memory _greeting)public{
greeting=_greeting;
}
function getGreeting()public view returns(string memory){
return greeting;
}
}
您可以通过传递字符串值使用greet()方法添加问候语,并使用getGreting()方法检索问候语。
1.在区块链网络上部署智能合约
a)创建项目:
mkdir pythonDapp
cd pythonDapp
truffle init
成功初始化项目后,转到您的文件夹并在/contracts目录中创建greeter.sol文件。在网络上部署合约之前,我们必须编译它并构建工件。
b)智能合约的编译:
因此,对于编译,我们将使用Truffle solc编译器。在您的主目录中,运行以下命令:
truffle compile
(or)
truffle.cmd compile#(for windows only)
上面的命令将在/contracts目录中编译你的合约,并在/build目录中创建二进制工件文件greeter.json。
c)部署合约:
打开您的Python IDLE编辑器,并在主目录deploy.py中使用以下代码创建一个新文件,然后在您的目录中运行py deploy.py。
import json
from web3 importWeb3,HTTPProvider
from web3.contract importConciseContract
#web3.py instance
w3=Web3(HTTPProvider("https://ropsten.infura.io/v3/"))
print(w3.isConnected())
key=""
acct=w3.eth.account.privateKeyToAccount(key)
#compile your smart contract with truffle first
truffleFile=json.load(open('./build/contracts/greeter.json'))
abi=truffleFile['abi']
bytecode=truffleFile['bytecode']
contract=w3.eth.contract(bytecode=bytecode,abi=abi)
#building transaction
construct_txn=contract.constructor().buildTransaction({
'from':acct.address,
'nonce':w3.eth.getTransactionCount(acct.address),
'gas':1728712,
'gasPrice':w3.toWei('21','gwei')})
signed=acct.signTransaction(construct_txn)
tx_hash=w3.eth.sendRawTransaction(signed.rawTransaction)
print(tx_hash.hex())
tx_receipt=w3.eth.waitForTransactionReceipt(tx_hash)
print("Contract Deployed At:",tx_receipt['contractAddress'])