版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
一智能合約開發(fā)語言:solidityIDE:mix-ideorwhatever實例編寫,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項目目錄結(jié)構(gòu).編寫合約代碼,保存到contracts/YourContractName.sol文件。.把合約名字加到config/app.json的'contracts'部分。.啟動以太坊節(jié)點(例如在另一個終端里面運行testrpc)。-truffledeploy(在truffle項目目錄中)添加一個智能合約。在truffleinit執(zhí)行后或是一個現(xiàn)有的項目目錄中,復(fù)制粘帖上面的會議合約到contracts/Conference.sol文件中。然后打開truffle.js文件,把'Conference'加入'deploy'數(shù)組中。19t"deploy":[20//Namesofcontractsthatshouldbedeployedtothenetwork.21"Conference"22],啟動testrpco在另一個終端中啟動testrpco編譯或部署。執(zhí)行truflecompile看一下合約是否能成功編譯,或者直接trufledeploy一步完成編譯和部署。這條命令會把部署好的合約的地址和ABI(應(yīng)用接口)加入到配置文件中,這樣之后的truffletest和trufflebuild步驟可以使用這些信息。出錯了?編譯是否成功了?記住,錯誤信息即可能出現(xiàn)在testrpc終端也可能出現(xiàn)在truffle終端。重啟節(jié)點后記得重新部署!如果你停止了testrpc節(jié)點,下一次使用任何合約之前切記使用truffledeploy重新部署。testrpc在每一次重啟之后都會回到完全空白的狀態(tài)。部署truffledeploy啟動服務(wù)truffleserve啟動服務(wù)后,可以在瀏覽器訪問項目:http://loca山ost:8080/三智能合約測試用例編寫//測試用例編寫〃把項目目錄test/中的example.js文件重命名為conference.js,內(nèi)容修改為如下,然后啟動testrpc后,運行//Truffletestcontract('Conference',function(accounts){//1.初始化一個新的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.測試合約函數(shù)調(diào)用測試改變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.測試交易調(diào)用一個需要發(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.測試包含轉(zhuǎn)賬的合約最后,為了完整性,確認一下refundTicket方法能正常工作,而且只有會議組織者能調(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編譯器提供了一個參數(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. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 承包荒山合同(2篇)
- 二零二五年度環(huán)保型排水溝建造與養(yǎng)護合同4篇
- 二零二五版新能源電動汽車充電設(shè)施建設(shè)服務(wù)合同范本2篇
- 2025年度二零二五年度民辦學(xué)校教師學(xué)術(shù)交流與合作合同4篇
- 二零二五年度出口貿(mào)易合同中英雙語不可抗力條款合同范本4篇
- 二零二五年度建筑外墻裝飾面磚采購合同3篇
- 二零二五年度廚師健康管理與職業(yè)發(fā)展規(guī)劃合同4篇
- 二零二五年度臨時工勞務(wù)派遣服務(wù)合同范本6篇
- 2025年度設(shè)施農(nóng)業(yè)大棚租賃合同范本4篇
- 2025年度個人房產(chǎn)買賣合同范本(含貸款及還款安排)4篇
- CJT 511-2017 鑄鐵檢查井蓋
- 配電工作組配電網(wǎng)集中型饋線自動化技術(shù)規(guī)范編制說明
- 職業(yè)分類表格
- 2024高考物理全國乙卷押題含解析
- 廣東省深圳高級中學(xué)2023-2024學(xué)年八年級下學(xué)期期中考試物理試卷
- 介入科圍手術(shù)期護理
- 青光眼術(shù)后護理課件
- 設(shè)立工程公司組建方案
- 設(shè)立項目管理公司組建方案
- 《物理因子治療技術(shù)》期末考試復(fù)習(xí)題庫(含答案)
- 退款協(xié)議書范本(通用版)docx
評論
0/150
提交評論