2018-07-09 14:53:11 1474瀏覽
區(qū)塊鏈如今正在深入人們的生活,本篇文章扣丁學(xué)堂區(qū)塊鏈培訓(xùn)小編和大家分享一下深入解析調(diào)用合約的方法,對(duì)區(qū)塊鏈開發(fā)感興趣的小伙伴就隨著小編一起來了解一下吧。
本文將講解這三種調(diào)用方法的區(qū)別:
testInstance.testFunc.sendTransaction(); 會(huì)創(chuàng)建一個(gè)交易,調(diào)用之后會(huì)返回一個(gè)交易hash值,它會(huì)廣播到網(wǎng)絡(luò),等待礦工打包, 它會(huì)消耗gas。
testInstance.testFunc.call(); 它完全是一個(gè)本地調(diào)用,不會(huì)向區(qū)塊鏈網(wǎng)絡(luò)廣播任何東西,它的返回值完全取決于testFunc 方法的代碼,不會(huì)消耗gas
testInstance.testFunc(); 它會(huì)比較特殊,由于有constant標(biāo)識(shí)的方法不會(huì)修改狀態(tài)變量,所以它不會(huì)被編譯器執(zhí)行。所以,如果testFunc() 有constant標(biāo)識(shí),它并不會(huì)被編譯器執(zhí)行,web3.js會(huì)執(zhí)行call()的本地操作。相反如果沒有constant標(biāo)識(shí),會(huì)執(zhí)行sendTransaction()操作。
寫個(gè)合約,代碼如下:
pragma solidity ^0.4.2; contract Test { uint public testMem; function testFunc1() returns (string resMes){ testMem++; resMes = "try to modify testMem,but has no constant label"; } function testFunc2() constant returns (string resMes){ testMem--; resMes = "try to modify testMem and has constant label"; } }
將合約部署到私有鏈,并獲取合約實(shí)例testInstance
調(diào)用testFunc1
> testInstance.testFunc1({from:eth.accounts[0]}) I0117 19:38:21.348763 internal/ethapi/api.go:1047] Tx(0x157d429be29953ea451ea95cf468a3a67c4a86e9b49d1b6b97cc15c579a27003) to: 0xc9bc867a613381f35b4430a6cb712eff8bb50310 "0x157d429be29953ea451ea95cf468a3a67c4a86e9b49d1b6b97cc15c579a27
可見,確實(shí)創(chuàng)建了一筆交易,開啟挖礦,等待打包…再查看下
> testInstance.testMem() 1 > eth.getTransaction('0x157d429be29953ea451ea95cf468a3a67c4a86e9b49d1b6b97cc15c579a27003') { blockHash: "0x9fa0c7d071e1d2e772de3f6f326595b9d9159b0056213416018c75f2d5c04ad2", blockNumber: 118, from: "0xcb1f9cd557b5dd81955a4df89e9b4c8a33023c12", gas: 90000, gasPrice: 20000000000, hash: "0x157d429be29953ea451ea95cf468a3a67c4a86e9b49d1b6b97cc15c579a27003", input: "0x561f5f89", nonce: 45, r: "0xb77558d48ab4efcaa24309b1003a7c4efabfdda26c3844c6aa18c58c6a08181a", s: "0x57fe6dde27fa7cfd2fb422e2adc9465125750b3271127b68bb65d496d99be531", to: "0xc9bc867a613381f35b4430a6cb712eff8bb50310", transactionIndex: 0, v: "0x1c", value: 0 }
可見,它確實(shí)是一筆交易,修改了合約的狀態(tài)變量,并且有90000的gas消耗。
再來試下testFunc2
> testInstance.testFunc2({from:eth.accounts[0]}) "try to modify testMem and has constant label"
確實(shí)只是在本地執(zhí)行,并沒有創(chuàng)建交易,所以更不會(huì)修改合約的狀態(tài)變量。
以上就是扣丁學(xué)堂區(qū)塊鏈在線學(xué)習(xí)小編給大家分享的深入解析調(diào)用合約的三種方法,希望對(duì)小伙伴們有所幫助,想要了解更多內(nèi)容的小伙伴可以登錄扣丁學(xué)堂官網(wǎng)咨詢??鄱W(xué)堂有專業(yè)的區(qū)塊鏈培訓(xùn)班,不僅有時(shí)俱進(jìn)的課程體系還有專業(yè)的老師授課,定能讓你輕松學(xué)習(xí),高薪就業(yè)??鄱W(xué)堂區(qū)塊鏈交流群:570711208。
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“區(qū)塊鏈培訓(xùn)技術(shù)資訊”的相關(guān)文章>>