[英]my smart contract is not responding and error saying web3 is not defined
[error saying web3 is not defined][1]<script>
var myContract;
async function CheckMetamaskConnection() {
// Modern dapp browsers...
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
try {
// Request account access if needed
await ethereum.enable();
// Acccounts now exposed
return true;
} catch (error) {
// User denied account access...
return false;
}
}
// Legacy dapp browsers...
else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Acccounts always exposed
return true;
}
// Non-dapp browsers...
else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
return false;
}
}
$(document).ready(async function () {
var IsMetamask = await CheckMetamaskConnection();
if (IsMetamask) {
myContract = await web3.eth.contract(SmartContractABI).at(SmartContractAddress);
getCandidate(1);
getCandidate(2);
await myContract.eventVote({
fromBlock:0
}, function(err, event){
console.log("event :", event);
getCandidate(event.args._candidateid.toNumber());
});
console.log("myContract :", myContract);
console.log("Metamask detected!")
} else {
console.log("Metamask not detected");
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'Metamask not detected!',
onClose() {
location.reload();
}
});
}
});
async function getCandidate(cad){
await myContract.candidates(cad, function(err, result){
if (!err) {
console.log("result : ", result);
document.getElementById("cad" + cad).innerHTML = result[1];
document.getElementById("cad"+cad+'count').innerHTML = result[2].toNumber();
}
});
}
async function Vote(cad){
await myContract.vote(cad, function(err, result){
if(!err){
console.log("We are winning!");
} else{
console.log("Can not connect to the smart contract");
}
})
}
</script>`
我的系統中有 node.js 和元掩碼(Windows 10)我從 github 克隆了你的項目並通過以下命令運行它
npm 安裝節點 index.js UI 在 localhost:3000 中完美部署,但是當我嘗試投票時,交易不起作用,然后我看到智能合約上的內容沒有呈現……然后我檢查了元掩碼。 哪個已連接並在 ropsten 網絡上有 1 個以太??? 然后我嘗試了 ganache(本地區塊鏈提供商),但交易仍然無法正常工作!!! 然后我將智能合約粘貼到 remix 中並獲取 ABI 和智能合約地址,但仍然無法正常工作!!! 然后我轉到瀏覽器的開發人員工具並看到以下錯誤!!!!...我不知道這個錯誤!!!!...我該如何解決這個問題???
錯誤可能是因為加載了 Web3. 請試試這個 function:
async loadWeb3(){
if(window.ethereum){
window.web3 = new Web3(window.ethereum)
await window.ethereum.request({ method: 'eth_requestAccounts' })
}
else if(window.web3){
window.web3 = new Web3(window.ethereum)
}
else{
window.alert("Non-Ethereum browser detected. You should consider trying MetaMask!")
}
}
另外,不要忘記在 javascript class 上添加導入:
import Web3 from 'web3'
並使用 npm 安裝導入:
npm i web3 --save
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.