為什麼事件日誌不顯示在 HTML 頁面中?
我想在 UI 中查看事件日誌。為此,我在 JavaScript 中使用以下程式碼:
var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'}); EnergyEvent.watch(function(err, result) { if (err) { console.log(err) return; } })
我的 JavaScript 程式碼中遺漏了什麼?
你可以在下面看到我的合約和 JavaScript 程式碼的完整程式碼:
堅固性程式碼:
pragma solidity ^0.4.15; import './SafeMath.sol'; import './Ownable.sol'; contract Weechain is Ownable{ using SafeMath for uint256; uint256 public energyTotalSupply; uint256 public powerTotalSupply; struct Device { uint256 energyValue; uint256 powerValue; } mapping(address => Device) amount; event setEnergyEvent(address indexed device, uint256 energy); event setPowerEvent(address indexed device, uint256 power); event setPayloadEvent(uint256 indexed SQN, string payload); // Constructor function Weechain() { energyTotalSupply = 0; powerTotalSupply = 0; amount[owner].energyValue = energyTotalSupply; amount[owner].powerValue = powerTotalSupply; } function amountOfenergy(address dev) constant returns (uint256 energy) { return amount[dev].energyValue; } function amountOfpower(address dev) constant returns (uint256 power) { return amount[dev].powerValue; } function setPayload(uint256 SQN, string payload) public returns (bool) { emit setPayloadEvent(SQN, payload); return true; } function setEnergy(address dev, uint256 energy) public returns(bool) { require(dev != address(0)); amount[dev].energyValue = amount[dev].energyValue.add(energy); energyTotalSupply = energyTotalSupply.add(energy); emit setEnergyEvent(dev, energy); return true; } function setPower(address dev, uint256 power) public returns (bool) { require(dev != address(0)); amount[dev].powerValue = amount[dev].powerValue.add(power); powerTotalSupply = powerTotalSupply.add(power); emit setPowerEvent(dev, power); return true; } }
Javascript 和 HTML 程式碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Weechain Smart Contract</title> <script src="./node_modules/web3/dist/web3.min.js"></script> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <style> html, body, h1, h2, h3, h4, h5, h6 { font-family: "Courier New", Courier, monospace } </style> <style> .input { background-color: #373E43; color: black; } </style> <style> .header { text-align: center; background-color: #373E43; color: white; } /* Clear floats after the columns */ .row:after { content: ""; display: table; clear: both; } /* Create three equal columns that floats next to each other */ .column { float: left; width: 33.33%; padding: 15px; } </style> <style> table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 8px; } tr:nth-child(odd){background-color: #373E43; color: white;} tr:nth-child(even){background-color: #373E43; color: white;} </style> <style> .output { background-color: #373E43; color: white; text-align: center; } </style> </head> <body> <div class="w3-container"> <div class="header"> <h1>Weechain</h1> </div> <!-- <p>Output: <span id="owner"></span> </p> --> <div class="output"> <p id="Output" > </p> </div> <div class="row"> <div class="input"> <div class="column"> <label for="name" class="col-lg-2 control-label">Device Address</label> <input id="Address" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <label for="name" class="col-lg-2 control-label">Energy</label> <input id="Energy" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <button id="buttonSet" class="w3-button w3-black w3-round-large">Set Energy Value</button> <button id="buttonGet" class="w3-button w3-black w3-round-large">Get Energy Balance</button> </div> <div class="column"> <label for="name" class="col-lg-2 control-label">Device Address</label> <input id="AddressPower" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <label for="name" class="col-lg-2 control-label">Power</label> <input id="Power" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <button id="buttonSetPower" class="w3-button w3-black w3-round-large">Set Power Value</button> <button id="buttonGetPower" class="w3-button w3-black w3-round-large">Get Power Balance</button> </div> <div class="column"> <label for="name" class="col-lg-2 control-label">Sequence Number</label> <input id="SQN" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <label for="name" class="col-lg-2 control-label">Payload</label> <input id="Payload" class="w3-input w3-border w3-animate-input" type="text" style="width:30%"> <button id="buttonSetPayload" class="w3-button w3-black w3-round-large">Set Payload Value</button> </div> </div> </div> <div class="row"> <div> <h2 class="sub-header">Energy Transactions</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Transaction Hash</th> <th>Device Address</th> <th>Energy Value</th> </tr> </thead> <tbody id="transactions"> </tbody> </table> </div> </div> </div> <div class="row"> <div> <h2 class="sub-header">Power Transactions</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Transaction Hash</th> <th>Device Address</th> <th>Power Value</th> </tr> </thead> <tbody id="transactionsPower"> </tbody> </table> </div> </div> </div> <div class="row"> <div> <h2 class="sub-header">Payload Transactions</h2> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Transaction Hash</th> <th>Payload</th> </tr> </thead> <tbody id="transactionsPayload"> </tbody> </table> </div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script> if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } //this.watchEvents = this.watchEvents.bind(this) web3.eth.defaultAccount = web3.eth.accounts[0]; /* var CoursetroContract = web3.eth.contract([{"constant":false,"inputs":[{"name":"_fName","type":"string"},{"name":"_age","type":"uint256"}],"name":"setInstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getInstructor","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]); */ var CoursetroContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"energyTotalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"dev","type":"address"}],"name":"amountOfenergy","outputs":[{"name":"energy","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"powerTotalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"dev","type":"address"},{"name":"energy","type":"uint256"}],"name":"setEnergy","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"SQN","type":"uint256"},{"name":"payload","type":"string"}],"name":"setPayload","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"dev","type":"address"}],"name":"amountOfpower","outputs":[{"name":"power","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"dev","type":"address"},{"name":"power","type":"uint256"}],"name":"setPower","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"device","type":"address"},{"indexed":false,"name":"energy","type":"uint256"}],"name":"setEnergyEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"device","type":"address"},{"indexed":false,"name":"power","type":"uint256"}],"name":"setPowerEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"SQN","type":"uint256"},{"indexed":false,"name":"payload","type":"string"}],"name":"setPayloadEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_by","type":"address"},{"indexed":true,"name":"_to","type":"address"}],"name":"ChangementOwnership","type":"event"}]); var Coursetro = CoursetroContract.at('0x8db88aaa4990408dfe41d6c77a76a09cba95d982'); /* var utils = require("./utils.js"); var _ = require("lodash"); var Promise = require("bluebird"); module.exports = { assertEvent: function(contract, filter) { return new Promise((resolve, reject) => { var event = contract[filter.event](); event.watch(); event.get((error, logs) => { var log = _.filter(logs, filter); if (log) { resolve(log); } else { throw Error("Failed to find filtered event for " + filter.event); } }); event.stopWatching(); }); } } */ /* var instructorEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'}); instructorEvent.watch(function(error, result){ alert(1); }); */ /* var event = testing.event_res(function(error, result) { if (!error) console.log(result.args); else console.log(error); }); */ var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'}); EnergyEvent.watch(function(err, result) { if (err) { console.log(err) return; } // append details of result.args to UI }) /* var instructorEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'}); instructorEvent.watch(function(error, EventLogs){ if (!error) { alert(1); console.log('Event Logs:' + EventLogs); } else console.log('Event Logs error:' + error); }); */ $("#buttonGet").click(function() { Coursetro.amountOfenergy($("#Address").val(), function(error, result) { if (!error) { $("#Output").html('Energy value of device with address ' + $("#Address").val() + ' equals '+ result.toString());//+' ('+result[1]+')'); console.log('Energy value of device with address \"' + $("#Address").val() + '" equals "'+ result.toString() + '"'); var receipt = web3.eth.getTransactionReceipt('0x5337d09cc54c1ec80970b7c74881f01cbf5653293873d54617b64fad21f6fb68'); console.log(' tx hash: ' + receipt.toString()); /*console.log("address\tfrom\t\tto\tamount\tblockHash\tblockNumber\tevent\tlogIndex\ttransactionHash\ttransactionIndex");*/ } else console.log(error); }); }); /* $("#buttonSet").click(function() { //Coursetro.setPayload($("#name").val(), $("#age").val()); Coursetro.setEnergy($("#Address").val(), $("#Energy").val()); //Coursetro.setPayload($("#name").val()); }); */ $("#buttonSet").click(function() { var estd_gas = Coursetro.setEnergy.estimateGas($("#Address").val(), $("#Energy").val()); console.log(estd_gas); var params = { gas: Math.round(estd_gas * 1.25), from: web3.eth.accounts[0] }; Coursetro.setEnergy.sendTransaction($("#Address").val(), $("#Energy").val(), params, function(error, TxHash) { if (!error) { $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')'); $('#transactions').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Address").val() + '</td><td>' + $("#Energy").val() + '</td></tr>') console.log(TxHash.toString()); //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4'); //var receipt2 = web3.toAscii(TxHash.input); //console.log(receipt.toString()); //Coursetro.setEnergyEvent({},{fromBlock: 0,toBlock: 'latest'}).watch((error, event) => {}) /*var EnergyEvent = Coursetro.setEnergyEvent({}, {fromBlock: 0, toBlock: 'latest'}); EnergyEvent.watch(function(err, result) { if (err) { console.log(err) return; } // append details of result.args to UI })*/ //console.log(receipt2.toString()); } else console.log(error); }); }); //// /////////////////////// $("#buttonSetPower").click(function() { var estd_gas = Coursetro.setPower.estimateGas($("#Address").val(), $("#Power").val()); console.log(estd_gas); var params = { gas: Math.round(estd_gas * 1.25), from: web3.eth.accounts[0] }; Coursetro.setPower.sendTransaction($("#Address").val(), $("#Power").val(), params, function(error, TxHash) { if (!error) { $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')'); $('#transactionsPower').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Address").val() + '</td><td>' + $("#Power").val() + '</td></tr>') console.log(TxHash.toString()); //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4'); //var receipt2 = web3.toAscii(TxHash.input); console.log(receipt.toString()); //console.log(receipt2.toString()); } else console.log(error); }); }); $("#buttonGetPower").click(function() { Coursetro.amountOfpower($("#Address").val(), function(error, result) { if (!error) { $("#Output").html('Power value of device with address ' + $("#Address").val() + ' equals '+ result.toString());//+' ('+result[1]+')'); console.log('Power value of device with address \"' + $("#Address").val() + '" equals "'+ result.toString() + '"'); //var receipt = web3.eth.getTransactionReceipt('0x5337d09cc54c1ec80970b7c74881f01cbf5653293873d54617b64fad21f6fb68'); console.log(' tx hash: ' + receipt.toString()); /*console.log("address\tfrom\t\tto\tamount\tblockHash\tblockNumber\tevent\tlogIndex\ttransactionHash\ttransactionIndex");*/ } else console.log(error); }); }); //////////////////// $("#buttonSetPayload").click(function() { var estd_gas = Coursetro.setPayload.estimateGas($("#SQN").val(), $("#Payload").val()); console.log(estd_gas); var params = { gas: Math.round(estd_gas * 1.25), from: web3.eth.accounts[0] }; Coursetro.setPayload.sendTransaction($("#SQN").val(), $("#Payload").val(), params, function(error, TxHash) { if (!error) { $("#Output").html('Transaction Hash in Hexadecimal:'+ TxHash.toString());//+' ('+TxHash[1]+')'); $('#transactionsPayload').append('<tr><td>' + TxHash.toString() + '</td><td>' + $("#Payload").val() + '</td></tr>') console.log(TxHash.toString()); //var receipt = web3.eth.getTransactionReceipt('0xc7be46f83e4c382995512357b99f97796b1e902c60d2667a068b062776a00dd4'); //var receipt2 = web3.toAscii(TxHash.input); console.log(receipt.toString()); //console.log(receipt2.toString()); } else console.log(error); }); }); //////////////// // TODO: trigger event when vote is counted, not when component renders </script> </body> </html>
注 1:我使用了本教程: https ://media.consensys.net/technical-introduction-to-events-and-logs-in-ethereum-a074d65dd61e
**更新:**我更改了關於使用者伊斯梅爾評論的 JavaScript 程式碼。但是,我仍然看不到事件日誌。
如果您想開發一個與智能合約互動的 Web 應用程序(發送交易、拉取事件等)。我真的建議你使用Truffle(編譯/部署/測試智能合約)和truffle-contract 庫(從網頁互動)。
智能合約
第 1 步:安裝松露
$ npm install -g truffle
第 2 步:初始化項目
$ truffle init
第 3 步:在“contract”文件夾中添加您的合約和庫(openzepellin)
$contracts$ ls -l -rw-rw-r-- 1 gjeanmart gjeanmart 515 May 13 17:34 Migrations.sol -rw-rw-r-- 1 gjeanmart gjeanmart 1010 Oct 26 1985 Ownable.sol -rw-rw-r-- 1 gjeanmart gjeanmart 1134 Oct 26 1985 SafeMath.sol -rw-rw-r-- 1 gjeanmart gjeanmart 1646 May 13 18:53 Weechain.sol
第 4 步:在“遷移”文件夾中編寫部署腳本
$ vi 1_initial_migration.js var Migrations = artifacts.require("./Migrations.sol"); module.exports = function(deployer) { deployer.deploy(Migrations); }; $ vi 2_deploy_contracts.js var Weechain = artifacts.require("./Weechain.sol"); module.exports = function(deployer) { deployer.deploy(Weechain) };
第 5 步:在“truffle.js”中編寫配置
module.exports = { networks: { development: { host: "localhost", port: 9545, network_id: "*" // Match any network id } } };
第 6 步:部署
執行
truffle develop
以執行沙盒乙太坊區塊鏈。$ truffle develop Truffle Develop started at http://127.0.0.1:9545/ Accounts: (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57 (1) 0xf17f52151ebef6c7334fad080c5704d77216b732 (2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef (3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544 (4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2 (5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e (6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5 (7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5 (8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc (9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de Private Keys: (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1 (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418 (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63 (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8 (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7 (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4 (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5 Mnemonic: candy maple cake sugar pudding cream honey rich smooth crumble sweet treat ⚠️ Important ⚠️ : This mnemonic was created for you by Truffle. It is not secure. Ensure you do not use it on production blockchains, or else you risk losing funds.
然後執行
migrate
以在此區塊鏈上部署您的智能合約。truffle(develop)> migrate Compiling ./contracts/Ownable.sol... Compiling ./contracts/SafeMath.sol... Compiling ./contracts/Weechain.sol... Compiling Ownable.sol... Compiling SafeMath.sol... Compilation warnings encountered: /home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:24:3: Warning: No visibility specified. Defaulting to "public". function Weechain() { ^ (Relevant source part starts here and spans across multiple lines). ,/home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:33:3: Warning: No visibility specified. Defaulting to "public". function amountOfenergy(address dev) constant returns (uint256 energy) { ^ (Relevant source part starts here and spans across multiple lines). ,/home/gjeanmart/workspace/personal/stackexchange/48396-why-event-log-is-not-shown-in-html-page/contracts/Weechain.sol:36:3: Warning: No visibility specified. Defaulting to "public". function amountOfpower(address dev) constant returns (uint256 power) { ^ (Relevant source part starts here and spans across multiple lines). Writing artifacts to ./build/contracts Using network 'develop'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0xcb0ccc3f1fbe419b96b95c6ef63e54ac8557061922702e89ae44e1c288508247 Migrations: 0x8cdaf0cd259887258bc13a92c0a6da92698644c0 Saving successful migration to network... ... 0xd7bc86d31bee32fa3988f1c1eabce403a1b5d570340a3a9cdba53a472ee8c956 Saving artifacts... Running migration: 2_deploy_contracts.js Deploying Weechain... ... 0x0bd3d3d1534c391abc50a1e3164499e45da9bb49b4501aa9fde3515440d50c7e Weechain: 0x345ca3e014aaf5dca488057592ee47305d9b3e10 Saving successful migration to network... ... 0xf36163615f41ef7ed8f4a8f192149a0bf633fe1a2398ce001bf44c43dc7bdda0 Saving artifacts... truffle(develop)>
您的智能合約現在部署在可通過 RPC 端點**http://localhost:9545**訪問的沙箱區塊鏈上,並創建以下帳戶並為每個帳戶提供 100 個乙太幣(這些帳戶可以導入 Metamask 中進行測試)
Accounts: (0) 0x627306090abab3a6e1400e9345bc60c78a8bef57 (1) 0xf17f52151ebef6c7334fad080c5704d77216b732 (2) 0xc5fdf4076b8f3a5357c5e395ab970b5b54098fef (3) 0x821aea9a577a9b44299b9c15c88cf3087f3b5544 (4) 0x0d1d4e623d10f9fba5db95830f7d3839406c6af2 (5) 0x2932b7a2355d6fecc4b5c0b6bd44cc31df247a2e (6) 0x2191ef87e392377ec08e7c08eb105ef5448eced5 (7) 0x0f4f2ac550a1b4e2280d04c21cea7ebd822934b5 (8) 0x6330a553fc93768f612722bb8c2ec78ac90b3bbc (9) 0x5aeda56215b167893e80b4fe645ba6d5bab767de Private Keys: (0) c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 (1) ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f (2) 0dbbe8e4ae425a6d2687f1a7e3ba17bc98c673636790f1b8ad91193c05875ef1 (3) c88b703fb08cbea894b6aeff5a544fb92e78a18e19814cd85da83b71f772aa6c (4) 388c684f0ba1ef5017716adb5d21a053ea8e90277d0868337519f97bede61418 (5) 659cbb0e2411a44db63778987b1e22153c086a95eb6b18bdf89de078917abc63 (6) 82d052c865f5763aad42add438569276c00d3d88a2d062d36b2bae914d58b8c8 (7) aa3680d5d48a8283413f7a108367c7299ca73f553735860a87b08f39395618b7 (8) 0f62d96d6675f32685bbdb8ac13cda7c23436f63efbb9d07700d8669ff12b7c4 (9) 8d5366123cb560bb606379f90a0bfd4769eecc0557f1b362dcae9012b548b1e5
Web應用程序
現在,Web 應用程序,您將看到,現在從您的網頁訪問智能合約非常簡單和乾淨。
第 1 步:使用 nodejs 為您的 Web 應用程序提供服務。創建文件
serve.js
$ npm i -s connect serve-static truffle-contract $ vi serve.js var connect = require('connect'); var serveStatic = require('serve-static'); connect().use(serveStatic(__dirname)).listen(8080, function(){ console.log('Server running on 8080...'); });
第 2 步:執行網路伺服器
$ node serve
現在您的 index.html
http://localhost:8080
頁面以及 Truffle 智能合約工件(一種包含所有內容的 JSON 文件:ABI、地址等)都可用http://localhost:8080/build/contracts/Weechain.json
第 3 步:初始化 Web3 並載入合約
// Load Web3 console.log("### LOAD WEB3") if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } console.log(web3) // Default account console.log("### DEFAULT ACCOUNT") web3.eth.defaultAccount = web3.eth.accounts[0]; console.log(web3.eth.defaultAccount) // Get Truffle Contract artefact console.log("### Get Truffle Contract artefact") var Coursetro; $.getJSON("http://localhost:8080/build/contracts/Weechain.json", function( data ) { console.log(data) // Load Contract var CoursetroContract = TruffleContract(data); CoursetroContract.setProvider(web3.currentProvider); // Get contract instance CoursetroContract.deployed().then(function(instance) { Coursetro = instance; console.log(Coursetro) }); });
第 4 步:發送交易並獲取收據觸發的事件
$("#buttonSet").click(function() { Coursetro.setEnergy($("#Address").val(), $("#Energy").val()).then(function(receipt) { console.log(receipt) console.log("Logs trigerred for this transaction:") console.log(receipt.logs) }).catch(function(error) { console.log(error) }); });
這展示了 Truffle 框架 (+Ganache) 如何抽象和簡化 Web3 開發的大部分複雜性。您提到的教程很好,但不幸的是 2016 年 6 月聽起來有點舊。區塊鏈技術正在迅速發展和發展!