版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
一智能合約開發(fā)語(yǔ)言:solidityIDE:mix-ideorwhatever實(shí)例編寫,Conference.sol:contractConference{addresspublicorganizer;mapping(address=>uint)publicregistrantsPaid;uintpublicnumRegistrants;uintpublicquota;eventDeposit(address_from,uint_amount);//soyoucanlogtheseeventseventRefund(address_to,uint_amount);functionConference。{//Constructororganizer=msg.sender;quota=500;numRegistrants=0;}functionbuyTicket()publicreturns(boolsuccess){if(numRegistrants>=quota){returnfalse;}registrantsPaid[msg.sender]=msg.value;numRegistrants++;Deposit(msg.sender,msg.value);returntrue;}functionchangeQuota(uintnewquota)public{if(msg.sender!=organizer){return;}quota=newquota;}functionrefundTicket(addressrecipient,uintamount)public{if(msg.sender!=organizer){return;}if(registrantsPaid[recipient]==amount){addressmyAddress=this;if(myAddress.balance>=amount){recipient,send(amount);registrantsPaid[recipient]=0;numRegistrants--;Refund(recipient,amount);}}}functiondestroy。{//sofundsnotlockedincontractforeverif(msg.sender==organizer){suicide(organizer);//sendfundstoorganizer}}}二智能合約部署使用truffle部署智能合約的步驟:.truffleinit(在新目錄中)=>創(chuàng)建truffle項(xiàng)目目錄結(jié)構(gòu).編寫合約代碼,保存到contracts/YourContractName.sol文件。.把合約名字加到config/app.json的'contracts'部分。.啟動(dòng)以太坊節(jié)點(diǎn)(例如在另一個(gè)終端里面運(yùn)行testrpc)。-truffledeploy(在truffle項(xiàng)目目錄中)添加一個(gè)智能合約。在truffleinit執(zhí)行后或是一個(gè)現(xiàn)有的項(xiàng)目目錄中,復(fù)制粘帖上面的會(huì)議合約到contracts/Conference.sol文件中。然后打開truffle.js文件,把'Conference'加入'deploy'數(shù)組中。19t"deploy":[20//Namesofcontractsthatshouldbedeployedtothenetwork.21"Conference"22],啟動(dòng)testrpco在另一個(gè)終端中啟動(dòng)testrpco編譯或部署。執(zhí)行truflecompile看一下合約是否能成功編譯,或者直接trufledeploy一步完成編譯和部署。這條命令會(huì)把部署好的合約的地址和ABI(應(yīng)用接口)加入到配置文件中,這樣之后的truffletest和trufflebuild步驟可以使用這些信息。出錯(cuò)了?編譯是否成功了?記住,錯(cuò)誤信息即可能出現(xiàn)在testrpc終端也可能出現(xiàn)在truffle終端。重啟節(jié)點(diǎn)后記得重新部署!如果你停止了testrpc節(jié)點(diǎn),下一次使用任何合約之前切記使用truffledeploy重新部署。testrpc在每一次重啟之后都會(huì)回到完全空白的狀態(tài)。部署truffledeploy啟動(dòng)服務(wù)truffleserve啟動(dòng)服務(wù)后,可以在瀏覽器訪問項(xiàng)目:http://loca山ost:8080/三智能合約測(cè)試用例編寫//測(cè)試用例編寫〃把項(xiàng)目目錄test/中的example.js文件重命名為conference.js,內(nèi)容修改為如下,然后啟動(dòng)testrpc后,運(yùn)行//Truffletestcontract('Conference',function(accounts){//1.初始化一個(gè)新的Conference,然后檢查變量是否都正確賦值it("Initialconferencesettingsshouldmatch",function(done){varconference=Conference.at(Conference.deployed_address);//sameaspreviousexampleuptohereConference.new({from:accounts[。]}).then(function(conference){conference.quota.call().then(function(quota){assert.equal(quota,500,"Quotadoesn'tmatch!");}).then(function(){returnconference.numRegistrants.call();
}).then(function(num){assert.equal(num,0,"Registrantsshouldbezero!");anizer.call();}).then(function(organizer){assert.equal(organizer,accounts[。],"Ownerdoesn'tmatch!");done();//tostopthesetestsearlier,movethisup}).catch(done);}).catch(done);});//2.測(cè)試合約函數(shù)調(diào)用測(cè)試改變Quote變量的函數(shù)能否工作it("Shouldupdatequota",function(done){varc=Conference.at(Conference.deployed_address);Conference.new({from:accounts[。]}).then(function(conference){conference.quota.call().then(function(quota){assert.equal(quota,500,"Quotadoesn'tmatch!");}).then(function(){returnconference.changeQuota(300);thetransactionhash}).then(function(result){//resulthereisatransactionhashconsole.log(result);//ifyouweretoprintthisoutit'dbelonghexreturnconference.quota.call()thetransactionhash}).then(function(quota){assert.equal(quota,300,"Newquotaisnotcorrect!");done();}).catch(done);}).catch(done);});//3.測(cè)試交易調(diào)用一個(gè)需要發(fā)起人發(fā)送資金的函數(shù)。it("Shouldletyoubuyaticket",function(done){varc=Conference.at(Conference.deployed_address);Conference.new({from:accounts[。]}).then(function(conference){varticketPrice=web3.toWei(.05,'ether');varinitialBalance=web3.eth.getBalance(conference.address).toNumber();conference.buyTicket({from:accounts[1],value:ticketPrice}).then(function。{varnewBalance=web3.eth.getBalance(conference.address).toNumber();vardifference=newBalance-initialBalance;assert.equal(difference,ticketPrice,"Differenceshouldbewhatwassent");returnconference.numRegistrants.call();}).then(function(num){assert.equal(num,1,"thereshouldbe1registrant");returnconference.registrantsPaid.call(accounts[1]);}).then(function(amount){assert.equal(amount.toNumber(),ticketPrice,"Sender'spaidbutisnotlisted");done();}).catch(done);}).catch(done);});//4.測(cè)試包含轉(zhuǎn)賬的合約最后,為了完整性,確認(rèn)一下refundTicket方法能正常工作,而且只有會(huì)議組織者能調(diào)用it("Shouldissuearefundbyowneronly",function(done){varc=Conference.at(Conference.deployed_address);Conference.new({from:accounts[。]}).then(function(conference){varticketPrice=web3.toWei(.05,'ether');varinitialBalance=web3.eth.getBalance(conference.address).toNumber();conference.buyTicket({from:accounts[1],value:ticketPrice}).then(function(){varnewBalance=web3.eth.getBalance(conference.address).toNumber();vardifference=newBalance-initialBalance;assert.equal(difference,ticketPrice,"Differenceshouldbewhatwassent");//sameasbeforeuptohere//Nowtrytoissuerefundasseconduser-shouldfailreturnconference.refundTicket(accounts[1],ticketPrice,{from:accounts[1]});}).then(function。{varbalance=web3.eth.getBalance(conference.address).toNumber();assert.equal(web3.toBigNumber(balance),ticketPrice,"Balanceshouldbeunchanged");//Nowtrytoissuerefundasorganizer/owner-shouldworkreturnconference.refundTicket(accounts[1],ticketPrice,{from:accounts[。]});}).then(function(){varpostRefundBalance=web3.eth.getBalance(conference.address).toNumber();assert.equal(postRefundBalance,initialBalance,"Balanceshouldbeinitialbalance");done();}).catch(done);}).catch(done);});});//Solidity編譯器提供了一個(gè)參數(shù)讓你可以從命令行獲取合約的Gas開銷概要//solc--gasConference.sol//輸出:=======Conference=======Gasestimation:construction:45438+271200=316638external:registrantsPaid(address):323organizer():282refundTicket(address,uint256):[]destroy():384TOC\o"1-5"\h\zchangeQuota(uint256):20370quota():333numRegistrants():355buyTicket():42023}}}}internal:四為合約創(chuàng)建DApp界面■■app/javascripts/app.jswindow.onload=function。{varaccounts=web3.eth.accounts;varconference=Conference.at(Conference.deployed_address);$("#confAddress").html(Conference.deployed_address);varmyConferencelnstance;Conference.new({from:accounts[。],gas:3141592}).then(function(conf){myConferencelnstance=conf;checkValues();});//CheckValuesfunctioncheckValues(){myConferenceInstance.quota.call().then(function(quota){$("input#confQuota").val(quota);returnmyConferenceIanizer.call();}).then(function(organizer){$("input#confOrganizer").val(organizer);returnmyConferenceInstance.numRegistrants.call();}).then(function(num){$("#numRegistrants").html(num.toNumber());returnmyConferenceIanizer.call();});//ChangeQuotafunctionchangeQuota(val){myConferenceInstance.changeQuota(val,{from:accounts[0]}).then(function。{returnmyConferenceInstance.quota.call();}).then(function(quota){if(quota==val){varmsgResult;msgResult="Changesuccessful";}else{msgResult="Changefailed";$("#changeQuotaResult").html(msgResult);});}//buyTicketfunctionbuyTicket(buyerAddress,ticketPrice){myConferenceInstance.buyTicket({from:buyerAddress,value:ticketPrice}).then(function(){returnmyConferenceInstance.numRegistrants.call();}).then(function(num){$("#numRegistrants").html(num.toNumber());returnmyConferenceInstance.registrantsPaid.call(buyerAddress);}).then(function(valuePaid){varmsgResult;if(valuePaid.toNumber()==ticketPrice){msgResult="Purchasesuccessful";}else{msgResult="Purchasefailed";$("#buyTicketResult").html(msgResult);functionrefundTicket(buyerAddress,ticketPrice){varmsgResult;myConferenceInstance.registrantsPaid.call(buyerAddress).then(function(result){if(result.toNumber()==0){$("#refundTicketResult").html("Buyerisnotregistered-norefund!");}else{myConferenceInstance.refundTicket(buyerAddress,ticketPrice,{from:accounts[0]}).then(function。{returnmyConferenceInstance.numRegistrants.call();}).then(function(num){$("#numRegistrants").html(num.toNumber());returnmyConferenceInstance.registrantsPaid.call(buyerAddress);}).then(function(valuePaid){if(valuePaid.toNumber()==0){msgResult="Refundsuccessful";}else{msgResult="Refundfailed";$("#refundTicketResult").html(msgResult);});});//createWalletvarmsgResult;varsecretSeed=lightwallet.keystore.generateRandomSeed();$("#seed").html(secretSeed);lightwallet.keystore.deriveKeyFromPassword(password,function(err,pwDerivedKey){console.log("createWallet");varkeystore=newlightwallet.keystore(secretSeed,pwDerivedKey);//generateonenewaddress/privatekeypairs//thecorrespondingprivatekeysarealsoencryptedkeystore.generateNewAddress(pwDerivedKey);varaddress=keystore.getAddresses()[0];varprivateKey=keystore.exportPrivateKey(address,pwDerivedKey);console.log(address);$("#wallet").html("0x"+address);$("#privateKey").html(privateKey);$("#balance").html(getBalance(address));//Nowsetksastransaction_signerinthehookedweb3provider//andyoucanstartusingweb3usingthekeys/addressesinks!switchToHooked3(keystore);});functiongetBalance(address){returnweb3.fromWei(web3.eth.getBalance(address).toNumber(),'ether');}//switchtohooked3webproviderwhichallowsforexternalTxsigning//(ratherthansigningfromawalletintheEthereumclient)functionswitchToHooked3(_keystore){console.log("switchToHooked3");varweb3Provider=newHookedWeb3Provider({host:"http://localhost:8545",//checkwhatusingintruffle.jstransaction_signer:_keystore});web3.setProvider(web3Provider);}functionfundEth(newAddress,amt){console.log("fundEth");varfromAddr=accounts[。];//defaultowneraddressofclientvartoAddr=newAddress;varvalueEth=amt;varvalue=parseFloat(valueEth)*1.0e18;vargasPrice=1000000000000;vargas=50000;web3.eth.sendTransaction({from:fromAddr,to:toAddr,value:value},function(err,txhash){if(err)console.log('ERROR:'+err)console.log('txhash:'+txhash+"("+amt+"inETHsent)");$("#balance").html(getBalance(toAddr));
});}//WireuptheUIelements$("#changeQuota").click(function(){varval=$("#confQuota").val();changeQuota(val);});$("#buyTicket").click(function(){varval=$("#ticketPrice").val();varbuyerAddress=$("#buyerAddress").val();buyTicket(buyerAddress,web3.toWei(val));});$("#refundTicket").click(function(){varval=$("#ticketPrice").val();varbuyerAddress=$("#refBuyerAddress").val();refundTicket(buyerAddress,web3.toWei(val));});$("#createWallet").click(function(){varval=$("#password").val();if(!val){"red");$("#password").val("PASSWORDNEEDED").css("color”"red");$("#password").click(function(){$("#password").val("").css("color","black");});}else{createWallet(val);});});$("#fundWallet").click(function(){varaddress=$("#wallet").html();fundEth(address,1);});$("#checkBalance").click(function(){varaddress=$("#wallet").html();$("#balance").html(getBalance(address));});//Setvalueofwallettoaccounts[1]$("#buyerAddress").val(accounts[1]);$("#refBuyerAddress").val(accounts[1]);};■■index.html<!DOCTYPEhtml><html><head><title>ConferenceDApp</title><linkhref='/css?family=Open+Sans:400,700,300'rel='stylesheet'type='text/css'><style>body{font-family:Arial,sans-serif;}.section{margin:20px;}button{padding:5px16px;border-radius:4px;}button#changeQuota{background-color:yellow;}button#buyTicket{background-color:#98fb98;}button#refundTicket{background-color:pink;}button#createWallet{background-color:#add8e6;}#seed{color:green;}</style><scripttype="text/javascript"src="https:〃/ajax/libs/jquery/1.11.3/jquery.min.js"></script><scriptsrc="./app.js"></script></head><body><h1>ConferenceDApp</h1><divclass="section">Contractdeployedat:<divid="confAddress"></div></div><divclass="section">Organizer:<inputtype="text"id="confOrganizer"/></div><divclass="section">Quota:<inputtype="text"id="confQuota"/><buttonid="changeQuota">Change</button><spanid="changeQuotaResult"></span></div><divclass="section">Registrants:<spanid="numRegistrants">0</span></div><hr/><divclass="section"><h2>BuyaTicket</h2>TicketPrice:<inputtype="text"id="ticketPrice"value="0.05"/>BuyerAddress:<inputtype="tex
溫馨提示
- 1. 本站所有資源如無(wú)特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 高中 食品 課程設(shè)計(jì)
- 2024年學(xué)年學(xué)校安全工作計(jì)劃
- 揚(yáng)塵專項(xiàng)施工方案
- 路肩拆除施工方案
- 2024石榴產(chǎn)業(yè)鏈上下游企業(yè)戰(zhàn)略合作合同3篇
- 課程設(shè)計(jì)折疊桌椅
- 2025年度文化創(chuàng)意產(chǎn)業(yè)項(xiàng)目投資合同4篇
- 年度梅酒競(jìng)爭(zhēng)策略分析報(bào)告
- 洗輪機(jī)施工方案
- 2025年度鐵路機(jī)車車輛維修與維護(hù)服務(wù)協(xié)議4篇
- (二統(tǒng))大理州2025屆高中畢業(yè)生第二次復(fù)習(xí)統(tǒng)一檢測(cè) 物理試卷(含答案)
- 口腔執(zhí)業(yè)醫(yī)師定期考核試題(資料)帶答案
- 2024人教版高中英語(yǔ)語(yǔ)境記單詞【語(yǔ)境記單詞】新人教版 選擇性必修第2冊(cè)
- 能源管理總結(jié)報(bào)告
- 充電樁巡查記錄表
- 阻燃材料的阻燃機(jī)理建模
- CJT 511-2017 鑄鐵檢查井蓋
- 配電工作組配電網(wǎng)集中型饋線自動(dòng)化技術(shù)規(guī)范編制說明
- 2024高考物理全國(guó)乙卷押題含解析
- 介入科圍手術(shù)期護(hù)理
- 青光眼術(shù)后護(hù)理課件
評(píng)論
0/150
提交評(píng)論