




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rè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é)點(例如在另一個終端里面運(yùn)行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后,運(yùn)行//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)賬的合約最后,為了完整性,確認(rè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)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 試論速生桉樹栽培技術(shù)與病蟲害防治措施
- 2025年老年健康管理長期照護(hù)服務(wù)模式與護(hù)理滿意度調(diào)查分析報告
- 不良資產(chǎn)處置行業(yè)市場格局報告:2025年創(chuàng)新模式與市場前景
- 2025年復(fù)合材料行業(yè)當(dāng)前發(fā)展趨勢與投資機(jī)遇洞察報告
- 2025年熔模精密鑄造行業(yè)當(dāng)前市場規(guī)模及未來五到十年發(fā)展趨勢報告
- 個人養(yǎng)老金制度調(diào)整對環(huán)保產(chǎn)業(yè)投資市場的機(jī)遇與挑戰(zhàn)研究報告
- 2025年無紡布行業(yè)當(dāng)前發(fā)展現(xiàn)狀及增長策略研究報告
- 學(xué)習(xí)六大紀(jì)律課件
- 2025年鋼鐵鑄件行業(yè)當(dāng)前市場規(guī)模及未來五到十年發(fā)展趨勢報告
- 2025年航空涂料行業(yè)研究報告及未來發(fā)展趨勢預(yù)測
- 輔導(dǎo)班勞務(wù)合同協(xié)議
- 宋代漢族服裝風(fēng)格演變及其社會功能
- T∕CWEA 29-2024 水利水電工程砌石壩施工規(guī)范
- 日本簽證個人信息處理同意書
- 新兵培訓(xùn)課件模板
- 2025年初中語文教師招聘面試八年級上冊逐字稿之愚公移山
- 自考《課程與教學(xué)論》考試復(fù)習(xí)題(附答案)
- 飼料粉塵清掃管理制度
- 四川天府銀行筆試內(nèi)容
- 有蹄類動物行為模式解析-全面剖析
- 維保工作管理制度
評論
0/150
提交評論