pragmasolidity^0.6.6;contractCoolNumberContract{uintpubliccoolNumber=10;functionsetCoolNumber(uint_coolNumber)public{coolNumber=_coolNumber;}}
<!DOCTYPEhtml><html><head><metacharset='utf-8'><metahttp-equiv='X-UA-Compatible'content='IE=edge'><title>Web3Demo</title><metaname='viewport'content='width=device-width,initial-scale=1'><scriptsrc='node_modules/web3/dist/web3.min.js'></script></head><body>Web3Demo<br><buttononclick="printCoolNumber();">PrintCoolNumber</button><buttononclick="changeCoolNumber();">ChangeCoolNumber</button><br/><br/>Status:<spanid="status">Loading...</span><scripttype="text/javascript"></script></body></html>
importWeb3from‘web3’;
npminstallweb3
asyncfunctionloadWeb3(){if(window.ethereum){window.web3=newWeb3(window.ethereum);window.ethereum.enable();}}asyncfunctionload(){awaitloadWeb3();updateStatus('Ready!');}functionupdateStatus(status){conststatusEl=document.getElementById('status');statusEl.innerHTML=status;console.log(status);}load();
asyncfunctionloadContract(){returnawaitnewwindow.web3.eth.Contract(ABI,contractAddress);}
asyncfunctionloadContract(){returnawaitnewwindow.web3.eth.Contract([{"inputs":[],"name":"coolNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_coolNumber","type":"uint256"}],"name":"setCoolNumber","outputs":[],"stateMutability":"nonpayable","type":"function"}],'0x5F4a8C71AFB0c01BA741106d418E78888607Ee63');}
asyncfunctionload(){awaitloadWeb3();window.contract=awaitloadContract();updateStatus('Ready!');}
asyncfunctionprintCoolNumber(){updateStatus('fetchingCoolNumber...');constcoolNumber=awaitwindow.contract.methods.coolNumber().call();updateStatus(`coolNumber:${coolNumber}`);}
asyncfunctionchangeCoolNumber(){constvalue=Math.floor(Math.random()*100);updateStatus(`UpdatingcoolNumberwith${value}`);constaccount=awaitgetCurrentAccount();constcoolNumber=awaitwindow.contract.methods.setCoolNumber(value).send({from:account});updateStatus('Updated.');}
constcoolNumber=awaitwindow.contract.methods.setCoolNumber(value).send({from:account});
asyncfunctiongetCurrentAccount(){constaccounts=awaitwindow.web3.eth.getAccounts();returnaccounts[0];}
Cruz Martinez
作者:链三丰,来源:区块链研究实验室
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。
郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。