您好,我在寻找类似问题时遇到了您的问题。
web3.eth 方法对我不起作用。
根据 MetaMask 有重大更改,请查看以下链接
https://medium.com/metamask/breaking-changes-to-the-metamask-provider-are-here-7b11c9388be9
按照这个
截至今天,MetaMask 已停止注入 window.web3,并对我们的 Ethereum Provider API (window.ethereum) 进行了有限数量的重大更改。
MetaMask 有遗留代码库,但他们不推荐它。
所以我们必须使用 window.ethereum 来代替 window.web3。 Web3 文档仍然有旧的方法和教程。没用。
就我而言,我正在尝试从 Dapp 大学转换现有的反应教程 (https://www.youtube.com/watch?v=CgXQC4dbGUE)
到
Angular 11、松露 (v5.4.1)、web3.js (v1.4.0)、Ganache。但无法保持平衡。
这是我的代码
import { Component, OnInit } from '@angular/core';
import Web3 from 'web3';
import DaiToken from '../../build/contracts/DaiToken.json';
import DappToken from '../../build/contracts/DappToken.json';
import TokenFarm from '../../build/contracts/TokenFarm.json';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
accounts: any;
investorAccount: string = '0x0';
daiToken: any = {};
dappToken: any = {};
tokenFarm: any = {};
daiTokenBalance: string = '0';
dappTokenBalance: string = '0';
stakingBalance: string = '0';
loading: boolean = true;
web3: any;
constructor() {}
ngOnInit() {
this.bootstrapWeb3();
}
async bootstrapWeb3() {
await this.loadWeb3();
await this.loadBlockchainData();
}
async loadWeb3() {
if (window.ethereum) {
// await window.ethereum.enable();
// no longer required, as line below does the same thing
this.accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
window.web3 = new Web3(window.ethereum);
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
}
async loadBlockchainData() {
this.web3 = window.web3;
// const accounts = await web3.eth.getAccounts(); <----- Not working with latest metamask changes
this.investorAccount = this.accounts[0];
try {
// Get networkId
const networkId = await window.ethereum.request({
method: 'net_version'
});
// const networkId = await web3.eth.net.getId().then(id => console.log(id)); // Not working
const daiTokenData = DaiToken.networks[networkId];
// Load DaiToken
if (daiTokenData) {
const daiToken = new window.web3.eth.Contract(DaiToken.abi, daiTokenData.address);
this.daiToken = daiToken;
// balanceOf not working
let daiTokenBalance = await daiToken.methods.balanceOf(this.investorAccount).call();
this.daiTokenBalance = daiTokenBalance.toString();
} else {
window.alert('DaiToken contract not deployed to detected network.');
}
} catch (error) {
console.log(error);
}
}
}
每当我尝试调用 window.web3.eth 或其他方法时,它都不会运行或返回任何错误。不确定需要进行哪些更改。
仍在寻找 MetaMask 和 web3.js 的最新更改的示例。找到后会尝试更新。
如果有人有关于最新 MetaMask、web3js 的更多信息,请分享。