智能合约是部署在区块链的代码,区块链本身不能执行代码,代码的执行是在本地的EVM中,实际上,部署在区块链上代码是能够在本地产生原智能合约代码的代码,可以理解区块链为一个数据库,而客户端从数据库中读取了存储的运行代码,并在本地运行后,将结果写入到了区块链这个数据库中。
Smart contracts are only programs stored on the blockchain,which will run when the predetermined conditions are met.They are often used to automate the execution of the agreement so that all participants can immediately determine the results without any middleman and without wasting time.They can also automatically complete the workflow and trigger the next operation when the conditions are met.
在区块链网络上部署智能合约
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/<API key>"))
print(w3.isConnected())
key="<Private Key here with 0x prefix>"
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'])